问题描述
- 需要一个异步任务计时器
-
应用中用到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>
解决方案二:
long time;
long difftime;
@Override
protected void onPreExecute(){
super.onPreExecute();
completed=false;
time = Calendar.getInstance().getTimeInMillis();
}
@Override
protected Boolean doInBackground(Integer... params) {
//code
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = Calendar.getInstance().getTimeInMillis() - time;
}
时间: 2024-12-30 01:33:36