AlertDialog未在AsyncTask中显示

时间:2015-06-11 19:27:31

标签: android android-asynctask

我有一个带有按钮的活动,该按钮启动AsyncTask

public void search(View view) {
    if (searchTask != null) {
        return;
    }

    searchTask = new SearchTask(this);
    searchTask.execute((Void)null);
}

这就是任务:

public class SearchTask extends AsyncTask<Void, Void, Boolean> {
    private final Activity activity;
    private final ProgressDialog dialog;

    public SearchTask(Activity activity) {
        this.activity = activity;
        this.dialog = new ProgressDialog(activity);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            wait(3000);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    protected void onPreExecute() {
        dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing())
            dialog.dismiss();
    }
}

我没有给get()打电话,所以我不应该阻止UI线程。问题是没有显示进度对话框。

这不是在AsynTask内显示对话框的正确方法吗?

2 个答案:

答案 0 :(得分:0)

wait()会导致IllegelMonitorException。应该在任务Thread.sleep()中应用延迟。

答案 1 :(得分:0)

从代码

下面删除 return; 后尝试
public void search(View view) {
    if (searchTask != null) {
        return;
    }

    searchTask = new SearchTask(this);
    searchTask.execute((Void)null);
}