我正在尝试了解在Android上使用AsyncTask
,并为此编写了这个简单的代码。
令人惊讶的是,doInBackground
方法被正确调用并且我看到了日志输出,但另外两个方法没有被调用。
我有什么遗漏吗?
public class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
try {
Log.i("Thread","1");
Thread.sleep(1000);
Log.i("Thread","2");
Thread.sleep(1000);
Log.i("Thread","3");
Thread.sleep(1000);
Log.i("Thread","4");
Thread.sleep(1000);
Log.i("Thread","5");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Void... progress) {
Log.i("Thread","onProgress");
}
protected void onPostExecute(Void... result) {
Log.i("Thread","onPosts");
}
}
[编辑]
这段代码在除了onProgressUpdate
之外都可以正常工作。
public class DownloadFilesTask extends AsyncTask<Void, Integer, String> {
public String doInBackground(Void... params) {
try {
int i = 0;
Log.i("Thread","1");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","2");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","3");
Thread.sleep(1000);
Log.i("Thread","4");
Thread.sleep(1000);
Log.i("Thread","5");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "done";
}
public void onProgressUpdate(int progress) {
Log.i("Thread","onProgress " + progress);
}
public void onPostExecute(String result) {
Log.i("Thread","onPosts " + result);
}
下面是我LogCat的截图:
注:LogCat是一种用于查看Android设备日志信息的工具。