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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With