78

我不明白为什么我会收到这个错误。我正在使用 AsyncTask 在后台运行一些进程。

我有:

protected void onPreExecute() 
{
    connectionProgressDialog = new ProgressDialog(SetPreference.this);
    connectionProgressDialog.setCancelable(true);
    connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    connectionProgressDialog.setMessage("Connecting to site...");
    connectionProgressDialog.show();

    downloadSpinnerProgressDialog = new ProgressDialog(SetPreference.this);
    downloadSpinnerProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    downloadSpinnerProgressDialog.setMessage("Downloading wallpaper...");
}

当我进入doInBackground()取决于条件时,我:

[...]    
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
[...]

每当我尝试时downloadSpinnerProgressDialog.show(),我都会收到错误。

有什么想法吗?

4

4 回答 4

106

该方法show()必须从用户界面(UI)线程调用,同时doInBackground()在不同的线程上运行,这是设计的主要原因AsyncTask

您必须拨打show()inonProgressUpdate()或 in onPostExecute()

例如:

class ExampleTask extends AsyncTask<String, String, String> {

    // Your onPreExecute method.

    @Override
    protected String doInBackground(String... params) {
        // Your code.
        if (condition_is_true) {
            this.publishProgress("Show the dialog");
        }
        return "Result";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        connectionProgressDialog.dismiss();
        downloadSpinnerProgressDialog.show();
    }
}
于 2010-09-01T03:16:46.237 回答
81

我有一个类似的问题,但通过阅读这个问题,我认为我可以在 UI 线程上运行:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

似乎对我有用。

于 2011-09-01T12:05:57.770 回答
1

我也很难完成这项工作,我的解决方案是同时使用 hyui 和 konstantin 的答案,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}
于 2012-05-16T10:08:03.007 回答
0
final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msgs) {
        //write your code hear which give error
        }
        }

new Thread(new Runnable() {
    @Override
    public void run() {
    handler.sendEmptyMessage(1);
        //this will call handleMessage function and hendal all error
    }
    }).start();
于 2012-03-28T12:13:34.767 回答