What Is AsyncTask and How Does it Work 1


When starting out with Android development, one of the challenges you may face is trying to update the user interface (UI) with new information. It’s simple to do if the information is something predetermined like a constant string. However, in most cases, you’ll find yourself needing to show new information that is stored in a database. In such a case, you will find yourself having to fetch data from a database and keeping your app responsive while it is fetching the data.

 

When retrieving data, you don’t want to wait for it to finish because that will stop the UI thread from responding to any user inputs, which results in an ANR (Application Not Responding) error. To get around the issue, you will need to create a worker thread to fetch the data in the background and then notify the UI when the data is available. But doing all this is such a hassle and that is where AsyncTask comes into the picture.


 

What Is AsyncTask?

 

AsyncTask enables proper and easy use of the UI thread. It allows you to perform background operations and publish the results to the UI thread without having to manipulate threads and handlers.

 

Something important to keep in mind is that AsyncTask is designed to be a helper class around Thread and Handler and is not part of a generic threading framework. Therefore, AsyncTasks are ideal for short operations (a few seconds). For long-running background tasks, you should use APIs provided in the `java.util.concurrent` package.

 

AsyncTask Generic Type

 

The AsyncTask has the following header:

private class MyTask extends AsyncTask<Params, Progress, Result> {...}

 

Params, progress, and result are generic types that can be anything and they get passed into the AsyncTask when execute.

 

The three types are used for the AsyncTask in the following way:

  • Params: the type of the parameters sent to the task upon execution
  • Progress: the type of the progress units published during the background computation
  • Result: the type of the result of the background computation

 

The 4 Steps of AsyncTask

 

 

When an AsyncTask is executed, the task goes through 4 steps in the following order:

  1. onPreExecute
    • Invoked by the UI thread before the task is executed
    • You would set up the UI portion of the task here such as showing a progress bar
  2. doInBackground(Params…)
    • Invokes on the background thread immediately after onPreExecute() finishes
    • This is the step to perform background computation or run the task
    • The parameters of the AsyncTask are passed to this step
    • The result of the task must be returned by this step and will be passed to the last step (onPostExecute)
    • In addition, this step can publish one or more units of progress to the UI by using publishProgress(Progress…).
  3. onProgressUpdate(Progress…)
    • This step is invoked on the UI thread after a call to publishProgress(Progress…)
    • This step is used to display any form of progress update while the background task is still executing.
  4. onPostExecute(Result)
    • This step is invoked on the UI thread after the background task finishes
    • The result of the background task is passed to this step as a parameter
    • Any update to the UI with the result from the background task is done here. For example, the data fetched from an API call.

 

Gotchas

 

When using AsynTask, you might run into some issues. So, here are some common issues you might run into and what you can do to resolve it.

 

The Generic Type Can’t Be Primitive Type

 

The generic type must be a reference type. There is eight primitive type in Java. They are byte, short, int, long, char, float, double, and boolean.

 

Task Is Still Running After You Invoke Cancel

 

This happens because `cancel` will cancel any following invocations to `doInBackground(Object[])`. The current running background task will still run until it returns. To ensure cancel takes effect as soon as possible, periodically check the return value of `isCancelled()` in the background task. After `cancel(true)` is invoke, any subsequent calls to `isCancelled()` will return true.


 

I hope this post was helpful to you. If you found this post helpful, share it with others so they can benefit too.

 

To get in touch, you can follow me on Twitter, leave a comment, or send me an email at steven@brightdevelopers.com.


About Steven To

Steven To is a software developer that specializes in mobile development with a background in computer engineering. Beyond his passion for software development, he also has an interest in Virtual Reality, Augmented Reality, Artificial Intelligence, Personal Development, and Personal Finance. If he is not writing software, then he is out learning something new.

One thought on “What Is AsyncTask and How Does it Work

Comments are closed.