在asynctasks中引用对象会阻止它更新UI

时间:2018-04-17 14:04:22

标签: java android android-asynctask

public class Container {

    public process(T result){
       // Update UI
    }

    public anotherMethodThatUpdatesUI(T result){
       // Update UI
    }
    public SomeTask extends AsyncTask<T,T,T> {
        private Container container;
        public someTask(Container container){
            this.container = container; 
        }

        protected void onPostExecute(T result) {
            super.onPostExecute(result);
            container.process(result);

        }
    }
}

我首先调用正常工作的AsyncTask execute方法。但在此之后调用anotherMethodThatUpdatesUI失败并出现此异常:

Can't create handler inside thread that has not called Looper.prepare()

但是如果我删除ContainerAsyncTask的尊敬并直接致电process。我没有收到错误。

public SomeTask extends AsyncTask<T,T,T> {
    private Container container;
    public someTask(Container container){
        // this.container = container; 
    }

    protected void onPostExecute(T result) {
        super.onPostExecute(result);
        process(result);
    }
}

1 个答案:

答案 0 :(得分:0)

你正在调用doInBackground中的anotherMethod fomr,因为你需要将另一个消息发布到原始消息,你可以使用doInBackground中的publishProgress并从AsyncTask处理onProgressUpdated方法。

public SomeTask extends AsyncTask<T,T,T> {
    private Container container;
    public someTask(Container container){
        this.container = container; 
    }
    public void doInBackground(T ... args) { 
         publishProgress(step1);
         publishProgress(step2);
         publishProgress(step3);
    }
    void onProgressUpdate(T step){
         anotherMethodThatUpdatesUI(step);
    }
}