【问题标题】:Android AsyncTask - onPostExecute not called (ProgressDialog)Android AsyncTask - 未调用 onPostExecute (ProgressDialog)
【发布时间】:2011-09-06 22:08:33
【问题描述】:

我有以下代码:

try {
    res = new Utils(ubc_context).new DownloadCalendarTask().execute().get();
} catch (InterruptedException e) {
    Log.v("downloadcalendar", "interruptedexecution : " + e.getLocalizedMessage());
    res = false;
} catch (ExecutionException e) {
    Log.v("downloadcalendar", "executionexception : " + e.getLocalizedMessage());
    res = false;
}

Log.v("displaymenu", "A");

public class Utils {

private Context context;

public Utils(Context context) {
    this.context = context;
}

public class DownloadCalendarTask extends AsyncTask<Void, Void, Boolean> {

    private ProgressDialog dialog;

    public DownloadCalendarTask() {

    dialog = new ProgressDialog(context);

    }

    protected void onPreExecute() {
        Log.v("preexecute", "A");
        dialog.setMessage("Loading calendar, please wait...");
        Log.v("preexecute", "B");
        dialog.show();
        Log.v("preexecute", "C");

    }

    protected Boolean doInBackground(Void... arg0) {
        // do some work here...
        return (Boolean) false;
    }

    protected void onPostExecute() {
        Log.d("utils", "entered onpostexecute");
        dialog.dismiss();
    }

}
}

代码的第一部分附加到按钮的onClick 侦听器。当我单击按钮时,按钮会闪烁(因为它确实表明它已被单击),然后在大约 8 秒后出现加载对话框但从未完成。

根据logcat,只要我点击按钮onPreExecute就会像Dialog.show()一样执行,所以我的第一个问题是为什么会有8秒的延迟?在这 8 秒内,logcat 显示正在执行 doInBackground。然而,根据 logcat(这是第二个问题),onPostExecute 永远不会被调用(因此 Dialog.dismiss())永远不会运行。

Logcat 显示 DownloadCalendarTask().execute().get() 之后的所有内容都在执行,所以就像 onPostExecute 刚刚被跳过一样。

非常感谢您的帮助!

【问题讨论】:

    标签: android android-asynctask progressdialog android-ui


    【解决方案1】:

    您正在调用 AsyncTask.get(),这会导致 UI 线程在 AsyncTask 执行时被阻塞。

    new DownloadCalendarTask().execute().get();
    

    如果您删除对 get() 的调用,它将异步执行并给出预期结果。

    new DownloadCalendarTask().execute();
    

    编辑: 您还需要更新 onPostExecute 方法的参数,它们需要包含结果。例如

    protected void onPostExecute(Boolean result) {
    

    【讨论】:

    • 谢谢,我试试这个。但是如果我删除 get() 是否还有一种简单的方法来检索 AysncTask 的结果?
    • 获取结果最简单的方法是让 AsyncTask 成为你的 Activity 的内部类,然后从 onPostExecute 方法调用你的 Activity 上的一个方法,将结果传递给 Activity。
    • 我已经做出了这个改变,ProgressDialog 现在立即出现了,但是现在 doInBackgroundAction 中的代码被执行并且它到达了 return 语句的结尾,但是它似乎什么也没做,并且进度对话框永远不会结束。同样,永远不会调用 onPostExecute
    • 我错过了您的 onPostExecute 有问题,您需要将结果添加为参数,我已经用它的语法更新了我的答案。如果您还没有浏览过documentation,可能值得浏览一下
    猜你喜欢
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2018-05-24
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多