AsyncTask

Only one thread can manipulate the user interface, e.g., call setText to write text in a TextView. The thread that does this is called the UI thread. It will usually be the main thread, i.e., the first thread that is created. To let another thread manipulate the UI indirectly, we passed Messages to and from a Handler here.

Another way to let another thread manipulate the UI indirectly is to create a subclass of the generic class AsyncTask. An AsyncTask with a doInBackground method is like a Thread with a run method. The AsyncTask eliminates the need for the Handler and Message; see Processes and Threads and Painless Threading.

doInBackground is executed by the non-main thread. Every other method of the AsyncTask, and in fact every other method of the entire app, is executed by the main thread. Do not call doInBackground, onProgressUpdate, or onPostExecute yourself. Allow them to be called automatically.

doInBackground should check during each loop to see if the non-main thread has been cancelled, since the main thread could cancel it at any time.

The three data types in the <angle brackets>

The three data types in the <angle brackets> of AsyncTask must be classes, not built-in types such as int or double. All three are used by the method doInBackground. The dots ... mean that an argument is an array.

  1. The first data type is the type of the argument(s) that the main thread passes to the execute method of the AsyncTask, or Void if there are no arguments. These arguments are then passed to the doInBackground method of the AsyncTask.

  2. The second data type is the type of the arguments that doInBackground passes to publishProgress. These arguments are then passed to onProgressUpdate.

  3. The third data type is the return type of doInBackground. This return value is then passed to onPostExecute.

Source code in Progress.zip

  1. ProgressActivity.java
  2. ProgressTask.java
  3. main.xml
  4. AndroidManifest.xml