Notes from AsynchTask chapter in Pro Android 4 book. Maybe you’ll find it helpful.
- Thread: if all you want to do is some computing, with no updates required to the UI, using a simple Thread object to offload some processing from the main thread works. This doesn’t work if you need to update the UI because the ANdroid UI toolkit is not thread safe so UI updates should always be updated only from the main thread.
- AsynchTask: convenient way of backgrounding some processing that wishes to update the UI. The AsynchTask takes care of creating a backgound thread for us where the work will get done, as well as providing callbacks that will run onthe main thread to allow easy access to the UT element (that is, views). The callbacks can fire before, during, and after our background thread has run.
AsynchTask is abstract, so need to customize it by extending it.
4 steps to an AsynchTask:
- Do any setup work in the onPreExecute() method. This method eecutes on the main thread.
- Run a background thread with doInBackground(). THread creation is all handled for us behind the scenes. THis code runs in a separate background thread.
- Update progess using publishProgresS() and onProgressUpdate(). publish Progress() gets called from within the code of doInBackground(), while onPreogressUpdate() is executed in the main thread as a result of the call to publishProgress(). With these two main methods, the backgrounded thread is able to communicate with the main thread while it i executing, so status updates can be made in the user interface before the gackgrounded thread has completed its work.
- Update the UI in onPostExecute() with the results. This method executes in the main thread.
- Steps 1 and 3 are optional.
- Note: only doInBackground() DOES NOT run on the main thread. So no updates to the UI from that function.