我正在写一个AsyncTask,如下所示:

class Load extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl) {
//do job seconds
//stop at here, and does not run onPostExecute
}
@Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
wait = false;
new Load().execute();
}
}


而另一种方法如下:

public void click() {
new Load().execute();
while(wait) {
;
}
}


等待是一个全局布尔值。

最佳答案

这段代码:

public void click() {
new Load().execute();
while(wait) {
;
}
}


执行任务时将阻止UI线程。这与仅在前台运行后台任务一样糟糕,并且应导致应用程序无响应(ANR)错误。请不要这样做。

请注意,如果取消任务,则不会调用AsyncTask.onPostExecute()。如果doInBackground引发异常,也不会调用它。 doInBackground中发生的任何事情都可能导致此问题。

关于android - AsyncTask不会调用onPostExecute(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9798396/

10-12 06:12