Android - AsyncTask

> Android

1 - About

The class AsyncTask simplify background thread creation.

  • The AsyncTask is not tied to the activity lifecycle. The virtual machine will hold the AsyncTask alive as long as the AsyncTask is running even if the onDestroy method is called. When rotating the device, the activity is destroyed and a new AsyncTask is created. There is then two tasks performing the same task.
  • The app has also to be in the foreground to instantiate the AsyncTask in the first place.

It's then not the best pattern for a very long background operation. See Android - Service (background operation without UI interaction)

Advertising

3 - Disadvantage

Note that when you start an AsyncTask, it is tied to the activity you start it in. When the activity is destroyed (which happens whenever the phone is rotated), the AsyncTask you started will refer to the destroyed activity and not the newly created activity. This is one of the reasons why using AsyncTask for a longer running task is dangerous. See loaders instead

4 - Implementation

There are four important methods to override:

  • onPreExecute - This method is run on the UI before the task starts and is responsible for any setup that needs to be done.
  • doInBackground - This is the code for the actual task you want done off the main thread. It will be run on a background thread and not disrupt the UI.
  • onProgressUpdate - This is a method that is run on the UI thread and is meant for showing the progress of a task, such as animating a loading bar.
  • onPostExecute - This is a method that is run on the UI after the task is finished.