嗨,我的应用程序中有AsyncTask,但我无法更改其setMessage

例如 :-

private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

        public ProgressTask1(MainActivity mainActivity) {
        context = mainActivity;
        dialog = new ProgressDialog(context);
    }

    private Context context;

    protected void onPreExecute() {

        this.dialog.setMessage("Checking system...");
        this.dialog.setCancelable(false);
        this.dialog.setTitle("Please Wait...");
        this.dialog.setIcon(R.drawable.ic_launcher);
        this.dialog.show();
    }


现在我想更改setmessage我尝试在doinbackground中添加它

    protected Boolean doInBackground(final String... args) {

    dothis1();
    this.dialog.setMessage("one done...");

dothis2();
this.dialog.setMessage("two done...");


但这正在使应用程序强制关闭,并且不要将其评级为低,因为我尽了最大努力并搜索了论坛,但能够解决此问题,因此请求在这个不错的社区提供帮助:)

有人可以帮忙吗? :)

错误


  05-13 23:36:34.899:E / AndroidRuntime(2454):原因:
  android.view.ViewRootImpl $ CalledFromWrongThreadException:仅
  创建视图层次结构的原始线程可以触摸其视图。

最佳答案

欧姆,您不应该从后台线程更新UI。要更新UI,可以通过以下两种方式进行:

1)使用publishProgress (Progress... values)onProgressUpdate(...)。为此,您必须更改您的AsynTask类:

 private class ProgressTask1 extends AsyncTask<String, String, Boolean> {

    //.......... //your init
    @Override
    protected Boolean doInBackground(String... params) {
        //your background handle

        //publish to change UI
        String toShow = "your_string_here";
        publishProgress(toShow);
        //return ...; //your return value
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //detect message and show it.
        //this.dialog.setMessage(values[0]);
    }
}


2)使用onPostExecute(....)

private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
    //.......... //your init

    @Override
    protected Boolean doInBackground(String... params) {
        //your background handle
        //return ...;//your return value
    }


    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        String toShow = "your_string_here";
        //this.dialog.setMessage(toShow);
    }
}

关于java - 一段时间后AsyncTask setMessage Android Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30221847/

10-09 16:01