Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make activity UI changes from an Android AsyncTask?

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 downsides I find problematic:

  1. It makes the source files very large, reducing efficiency in managing the code
  2. It makes it hard to reuse the thread class

What's a good solution? Use an inner class, but abstract everything it does to other classes? Pass a reference to the Activity to the AsyncTask? Always define the AsyncTask class as an inner class and just accept source files will be large?

like image 488
Ollie C Avatar asked Jan 29 '11 11:01

Ollie C


1 Answers

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.

like image 82
Heiko Rupp Avatar answered Sep 28 '22 01:09

Heiko Rupp