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:
- 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.
- doInBackground(Params… ) is called right after onPreExecute finishes and uses the background thread. This is where you’ll doing your work.
- 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.
- onPostExecute(Result) is called right after ‘doInBackground’ finishes and uses the UI thread.
- 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!
Resources
- GitHub Project
- AsyncTask – Docs