How to make activity UI changes from an Android AsyncTask?

后端 未结 3 975
深忆病人
深忆病人 2021-01-17 20:23

In a scenario where I have a UI that will be updated from a separate thread (using AsyncTask), I can define the AsyncTask as an inner class of the activity, but this has two

相关标签:
3条回答
  • 2021-01-17 20:46

    First and foremost: when using an AsyncTask you must not do UI activity within doInBackground().

    What you can do is - if you want to e.g. update status for a long running background job, is to publishProgress(values) from doInBackground(). The runtime will then for those values call your onProgressUpdate(values) callback, which runs in the UI thread and from where you can update the UI.

    Have a look at e.g. https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/TweetListActivity.java#L336 to see an example.

    The AsyncTask can be implemented in an own class file.

    0 讨论(0)
  • 2021-01-17 20:46

    I have a somewhat odd P.O.V with AsyncTasks because I generally prefer using normal Threads, but essentially the way I perform a background task and update a UI is create a Handler at the end of the onCreate() method, I'll then override the handleMessage(Message msg) method.

    Then in my Thread, I'll pass the Handler in as a parameter, then when I wish to make an update I'll send a message from the thread to the Handler, now what this does is communicate from the new background thread onto the UI thread to process work on the UI.

    Now I imagine AsyncTasks perform a similar task but removes the need to implement override the Handlers' handleMessage method.

    It'd be interesting learning more about any advantages / disadvantages between these two approaches.

    0 讨论(0)
  • 2021-01-17 20:53

    Quite a few examples I have seen just pass a Context into the constructor of the AsyncTask.

    public class BackgroundStuff extends AsyncTask<Void, Void, Void> {
        ...
        Context mContext;
        ...
        BackgroundStuff(Context context){
            super();
            this.mContext = context;
        }
        ...
    }
    

    I would be interested to hear if anyone else uses any other approaches.

    0 讨论(0)
提交回复
热议问题