LearnAll About Android AsyncTasks

Photo by Max DeRoin / CC0

Ben Deitch
writes on May 24, 2017

Let’s say you need to download a few images when you click a button. What would be the best way to do it? Well, since you wouldn’t want to interrupt the main/UI thread (and run the risk of showing your users an ANR dialog), you’d start by doing the downloading itself on a separate thread. Then, when the download is finished, you’d need to execute code on the UI thread again to update the UI with your new images. Also, if you wanted to show an updating progress bar, you’d need to run code on the UI thread for every progress update too!

Luckily, with the runOnUiThread method, this isn’t too difficult. But another way we could solve this problem would be to use an AsyncTask. AsyncTasks give us an easy way to do work on a separate thread while displaying the results of that work on the main thread. It handles all the threading behind the scenes and lets us focus on writing our app.

Related Reading: The Beginner’s Guide to Android

To create an AsyncTask you start by extending the AsyncTask class. This class has five helpful methods we can override to help us deal with our tasks:

  1. onPreExecute is called before your task is executed and uses the UI thread. If your task requires any setup, this is the place to do it.
  2. doInBackground(Params… ) is called right after onPreExecute finishes and uses the background thread. This is where you’ll doing your work. 
  3. onProgressUpdate(Progress… ) is called on the UI thread and is used to display progress to the user while the task is running (e.g. a progress bar). You can trigger a call to ‘onProgressUpdate’ by calling the ‘publishProgress’ method.
  4. onPostExecute(Result) is called right after ‘doInBackground’ finishes and uses the UI thread.
  5. onCancelled(Result) also uses the UI thread, and is only called if the task is cancelled.

When you extend the AsyncTask class you’ll need to add angle brackets and provide three types corresponding to the parameters you’d like to use for the ‘doInBackground’, ‘onProgressUpdate’, and ‘onPostExecute’ functions.

class MyAsyncTask extends AsyncTask<URL, Integer, Bitmap[]> {
    // ...

So for this example, we’d like to pass in URLs to ‘doInBackground’, Integers to ‘onProgressUpdate’, and an array of Bitmaps to ‘onPostExecute’. And if we use ALT+ENTER to have Android Studio implement these methods, it would look something like this:

* The …s are just a way to pass arrays into a function. So ‘urls’ is an array of URL objects, and we can start our task with an array of URLs by just continuing to add more URL parameters:

new MyAsyncTask().execute(url1, url2, url3, url4, url5, url6);

Now that we’ve got the bones of our task, let’s start adding in some code to download the images. For this example, to make things easy, instead of using a bunch of different URLs we’re just going to use one URL that serves up random images. So to start our AsyncTask with 10 images, we’d have something like this:

URL url = new URL("https://placeimg.com/640/480/any");
new MyAsyncTask().execute(url, url, url, url, url, url, url, url, url, url);

Then, inside the ‘doInBackground’ method, we need to turn those URLs into an array of Bitmaps. We should also call the ‘publishProgress’ method to trigger a call to ‘onProgressUpdate’ where we can update a ProgressBar.

Finally, in ‘onPostExecute’ we should hide the progress bar and add our Bitmaps to the layout:

AsyncTasks are a great way to do work on a separate thread and then use the results of that work to update the UI. However, if your task really is to download images then you might want to take a look at Picasso; it’s a library that makes this whole process incredibly easy for images!

Also, if you’re looking to learn more about Android development, then I suggest you start here. We’ll take you from novice to Android developer one step at a time and explain everything along the way. On the other hand, if you’re looking for something a bit more advanced and you’d like to gain a better understanding of what Threads are and how to use them, then I strongly encourage you to check out our Threads and Services course. It’ll give you all the information you need to feel confident building apps that do work in the background!

Want to further develop your coding skills? Check out the Treehouse 7-day free trial today!



Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop