AsyncTask usage summary

AsyncTask01

Overview

AsyncTask is useful when you are working on UI (main) thread, and want to do some (maybe long) background process, and want to get callback after the background process finishes. For example, consider the case when you want to update UI of Activity according to the result of internet access. You must execute URLconnection in background thread, while updating UI must be done in UI thread after getting result. It can be implemented without caring about threads or handlers by using AsyncTask. 

Basics

4 Steps method execution flow

AsyncTask01

AsyncTask – method sequence

  1. onPreExecute: invoked on the UI thread, before doInBackground starts. Initial set up part.
  2. doInBackground: invoked on the background thread. Long computation/process (ex. downloading) is executed in this method. It must be overriden.
  3. onProgressUpdate: invoked on the UI thread, during doInBackground. It is invoked after doInBackground method calls publishProgress to update UI of background process progress.
  4. onPostExecute: invoked on the UI thread, after doInBackground finishes. Final UI update part. 

The purpose to use AsyncTask is usually updating UI according to the result of background task, so at least you usually implement 2. doInBackground (MUST) and 4. onPostExecute.
(If you only need background process and callback to main thread is not necessary, just use Thread.start() or Handler.post() )

 

3 Types declaration 

AsyncTask is used by extending the class to your custom Class. You need to specify 3 types when extending AsyncTask.

  1. Params: input parameter, used in doInBackground method.
  2. Progress: the parameter passed from doInBackground to onProgressUpdate via publishProgress(Progress...)
  3. Result: return parameter of doInBackground,which is passed to onPostExecute.

※ If not necessary, just set Void type for each.

 

Usage – template

  • AsyncTask side 

Create subclass of AsyncTask. As written in Advance, it may be implemented as a inner class of Activity class.

  • Execution side

Usually the purpose is to update the UI, so execution is done from Activity/Fragment class.

Note that even type of “params”  is Void, the variables can be passed by Constructor. This is useful tip when you want to pass/input more than 2 types of variable.

 

More concrete examples

For example, refer AsyncTask Android example.

Advance

AsyncTask is usually used with Activity/Fragment, while the background task may be completely independent process from Activity itself. So the question comes up: how to establish independency between Activity & AsyncTask? which is the next topic

Reference

Sponsored Links