2 developerwab developerWab 于 2013.01.16 16:58 提问

需要一个异步任务计时器

应用中用到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;
  }

2个回答

Kill_it
Kill_it   2013.01.16 17:35
已采纳

我运行了,你的代码可以执行

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>
Kakalapa1986
Kakalapa1986   2013.01.16 17:33
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;
}
Csdn user default icon
上传中...
上传图片
插入图片