Understanding how to use Android AsyncTask

Understanding how to use Android AsyncTask

AsyncTask is an abstract category made available by Android which assists us to make use of the UI thread correctly. This class permits us to carry out long/background operations and displays its result on the UI thread without having to manipulate threads.

When to make use of AsyncTask?

Android carries out one thread model and whenever an android application is launched, a thread is created. Assuming we are carrying out network operation on a button click in our application.

On button click a request would be made to the server and response will be awaited. As a result of single thread model of android, till the time response is being waited for awaited our screen is non-responsive.

Therefore we ought to stay away fro carrying out long running operations on the UI thread. This is made up of file and network access.

To conquer this we can produce new thread and carry out run procedure to do this network call, so UI remains responsive.

But because Android follows single thread model and Android UI toolkit is not thread safe, therefore if there is a requirement to make a few alteration to the UI based on the result of the operation carried out, then this technique may result to a few issues.

Therefore, the Android framework has offered an  extremely good pattern which is enshrined into AsyncTask. 

AsyncTask ought to in an ideal world be used for operations that take few seconds. A few tasks keep the thread running for long time, therefore in such situations, it is recommended to utilize java.util.concurrent package like Executor, ThreadPoolExecutor and FutureTask.

AsyncTask is made up of four steps:

  1. doInBackground: Code carrying out long running operation goes in this method.  When onClick technique is carried out on click of button, it calls execute technique which accepts parameters and routinely calls doInBackground technique with the parameters passed.
  2. onPostExecute: This technique is called after doInBackground technique finishes processing. Result from doInBackground is passed to this category.
  3. onPreExecute: This technique is called before doInBackground technique is called.
  4. onProgressUpdate:This technique is called by calling publishProgress anytime from doInBackground call this technique.

The task can be cancelled by invoking cancel(boolean) technique. This will make following calls to isCancelled() to return true. After calling this technique, onCancelled(Object) technique is called rather than of onPostExecute() after doInBackground() returns.

 How to make use of AsyncTask?

 Example application

In this sample application we made the procedure to sleep for a few periods of time rather than performing network operation. (Just to offer explanation of the concept of AsyncTask. This is not a real-time application).

In the UI thread user inputs a value (time in milli seconds) which will be passed to AsyncTaskRunner.

AsyncTaskRunner is a private class which extends AsyncTask.

When the user clicks on the Run Async Task button, we make the process to sleep for a specific period of time. At the same time we keep the UI thread responsive by presenting  the status to the user.

Steps to create the application:

Generate new android application project in eclipse with default settings.

Produce the layout for the application.

Generate the MainActivity and AsyncTaskRunner at com.example.asynctaskdemo.MainActivity.java

Run the application


AsyncTask allows  the right and simple use of the UI thread. This class permits us to carry out background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is specified by a calculation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is specified by 3 generic types,  known as Params, Progress and Result, and 4 steps, known as onPreExecute, doInBackground, onProgressUpdate and onPostExecute


AsyncTask ought to be subcategorized to be used. The subcategory will override at least one procedure (doInBackground(Params…)), and most frequently will override a second one (onPostExecute(Result).)

Below is an example of subcategorization:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

protected Long doInBackground(URL... urls) {
   int count = urls.length;
   long totalSize = 0;
   for (int i = 0; i < count; i++) {
      totalSize += Downloader.downloadFile(urls[i]);
      publishProgress((int) ((i / (float) count) * 100));
      if (isCancelled()) break;
   return totalSize;

protected void onProgressUpdate(Integer... progress) {

protected void onPostExecute(Long result) {
   showDialog("Downloaded " + result + " bytes");

Once produced, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask’s generic types

The three types used by an asynchronous task are as follows:

  1. Params: This is the form of the parameters sent to the task upon execution.
  2. Progress: This is the form of the progress units published during the background calculation.
  3. Result: This is the form of the result of the background calculation.

Not  all forms are constantly made use of by an asynchronous task. To mark a type as unused, merely make use of the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { … }

Cancelling a task

A task can be cancelled at any time by calling cancel(boolean). Calling this method will make subsequent calls to isCancelled() to return true. After calling this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To make sure that a task is cancelled as fast as possible, you ought to constantly check the return value of isCancelled() at times from doInBackground(Object[]), if likely (within a loop for example.)

Threading rules

There are a few threading rules that ought to be followed for this class to work correctly:

  • The AsyncTask class ought to be loaded on the UI thread. This is carried out routinely as of JELLY_BEAN.
  • The task example ought to be produced on the UI thread.
  • execute(Params…) ought to be called on the UI thread.
  • Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually.
  • The task can be carried out only once (an exception will be propelled if a second execution is attempted.)

Observation of Memory

AsyncTask certifies that every callback calls are organized in such a way that the following operations are safe without explicit synchronizations.

  • Set member fields in the constructor or onPreExecute(), and refer to them in doInBackground(Params…).
  • Set member fields in doInBackground(Params…), and refer to them in onProgressUpdate(Progress…) and onPostExecute(Result).

Order of execution

When first introduced, AsyncTasks were carried out serially on one background thread. Beginning with DONUT, this was altered to a pool of threads permitting a lot of tasks to function in parallel. Beginning with HONEYCOMB, tasks are carried out on one thread to avoid widespread application errors caused by parallel execution.

If you actually desire parallel execution, you can call executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

Nested Categories

enumAsyncTask.StatusShows the present status of the task.


public static final ExecutorSERIAL_EXECUTORAn Executor that caries out tasks one at a time in serial order.
public static final ExecutorTHREAD_POOL_EXECUTORAn Executor that can be made use of in carrying out tasks in parallel.

Public Constructor

AsyncTask() Creates a new asynchronous task.

Public Methods

final Booleancancel(boolean mayInterruptIfRunning)
Tries to cancel execution of this task.
static voidThis carries out execute(Runnable runnable)
Convenience version of execute(Object) for use with a simple Runnable object.
final AsyncTaskThis execute(Params... params)
Executes the task with the specific factors.
final AsyncTaskThis executeOnExecutor(Executor exec, Params... params)
Executes the task with the particular factors.
final Resultget(long timeout, TimeUnit unit)
Waits if required for at most the given time for the calculation to finish, and then retrieves its result.
final Resultget()
Waits if required for the calculation to complete, and then retrieves its result.
final AsyncTask.StatusgetStatus()
Returns the present status of this task.
final BooleanisCancelled()
Returns true if this task was annulled before it finished generally.


public static final Executor SERIAL_EXECUTOR

Added in API level 11

This is an Executor that executes tasks one at a time in serial order. This serialization is  worldwide to a specific process.

public static final Executor THREAD_POOL_EXECUTOR

This is an Executor that can be used to execute tasks in parallel.

Public Constructors

public AsyncTask ()

Added in API level 3

This produces a new asynchronous task. This constructor ought to be invoked on the UI thread.

Public Methods

public final boolean cancel (boolean mayInterruptIfRunning)

This is incorporated in API level 3

This tries to cancel execution of this task. This attempt will fail if the task has already finished, already been cancelled, or could not be cancelled for a few other reason. If it does well, and this task has not begun when cancel is called, this task ought to never run. If the task has already begun, then it mayInterruptIfRunning factor determines if the thread executing this task ought to be interrupted in an effort to stop the task.

Calling this technique will lead to onCancelled(Object) being called on the UI thread after doInBackground(Object[]) returns. Calling this technique certifies that onPostExecute(Object) is never invoked. After invoking this category, you ought to check the value returned by isCancelled() periodically from doInBackground(Object[]) to complete the task as soon as possible.

  • false if the task could not be cancelled, typically because it has already completed normally; true otherwise

public static void execute (Runnable runnable)

Added in API level 11

Convenience edition of execute(Object) for utilization with a simple Runnable object.

public final AsyncTask<Params, Progress, Result> execute (Params… params)

Added in API level 3

Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it.

This technique must be called on the UI thread.

  • This instance of AsyncTask.
public final AsyncTask<Params, Progress, Result> executeOnExecutor (Executor exec, Params… params)

Added in API level 11

Executes the task with the particular factors parameters. The task returns itself (this) so that the caller can keep a reference to it.

This method is typically used with THREAD_POOL_EXECUTOR to permit a lot of tasks to run in parallel on a pool of threads taken care of by AsyncTask, nevertheless, you can as well make use of your own Executor for customized behavior.

Permitting many tasks to run in parallel from a thread pool is commonly not what you want, due to the fact that the order of their function is not specific.

For instance, if these tasks are made use of to alter any state in common (like writing a file as a result of a button click), there are no sureties on the order of the modifications.

Without careful task it is possible in uncommon situations for the newer edition of the data to be over-written by an older one, resulting to unclear data loss and stability issue that type of task is serialized irrespective of platform edition you can use this function with SERIAL_EXECUTOR.


Add a Comment