AsyncTask不会调用onPostExecute()

时间:2012-03-21 03:55:54

标签: android asynchronous android-asynctask

我正在撰写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) {
;
}
}

等待是一个全局布尔值。

4 个答案:

答案 0 :(得分:4)

此代码:

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

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

请注意,如果取消任务,则不会调用AsyncTask.onPostExecute()。如果doInBackground抛出异常,也不会调用它。无论doInBackground中发生了什么,都可能导致这种情况发生。

答案 1 :(得分:3)

这是proppar方式asynctask,你不会在任何其他方法中使用等待或睡眠都是
使用相同的常规方法

private class AsyncTask extends AsyncTask<Void, Void, Void> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {

        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            progressDialog.dismiss();

        }
    }

答案 2 :(得分:2)

您的doInBackground()方法看起来正在抛出Exception,请尝试将其放入try-catch块。
另外我不知道你为什么要调用super.onPostExecute(),尝试删除它,没有必要使用这个语句。

答案 3 :(得分:2)

您的while(wait){}循环阻止了UI线程。 onPostExecute在UI线程上运行。由于您正在阻止,onPostExecute永远无法执行。此外,您正在创建Load AsyncTask的新实例并在onPostExecute中执行它,这意味着除非您在某个时候取消,否则您将拥有无限循环。

相关问题