How to make activity UI changes from an Android AsyncTask?

后端 未结 3 979
深忆病人
深忆病人 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题