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:
- It makes the source files very large, reducing efficiency in managing the code
- 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?
Quite a few examples I have seen just pass a
Context
into the constructor of theAsyncTask
.I would be interested to hear if anyone else uses any other approaches.
First and foremost: when using an
AsyncTask
you must not do UI activity withindoInBackground()
.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 youronProgressUpdate(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.
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.