應用中用到AsyncTask調用網頁服務,然後解析xml文件,我知道開始到結束的持續時間,用了下面的方法之後,獲取的時間總是0
:
@Override
protected void onPreExecute(){
super.onPreExecute();
completed=false;
time = System.currentTimeMillis();
}
protected Boolean doInBackground(Integer... params) {
//code
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
}
我運行了,你的代碼可以執行
private class TestTask extends AsyncTask<Integer, Void, Boolean> {
private long time;
@Override
protected void onPreExecute() {
super.onPreExecute();
time = System.currentTimeMillis();
}
@Override
protected Boolean doInBackground(Integer... params) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TestTask", "difftime = "
+ (System.currentTimeMillis() - time));
}
}
檢查一下AsyncTask的簽名 :
extends AsyncTask<Integer, Void, Boolean>