Tuesday, March 19, 2013

Android AsyncTasks (MultiThreading)

This tutorial explains what AsyncTasks are in Android, why you should use them, and demonstrates a simple app that calculates prime numbers to show them in action.

1. What is an AsyncTask and Why Should I use Them?

AsyncTasks are asynchronous because they operate in a thread separate from the UI thread.

You should use them to complete performance intensive tasks or tasks that may complete in an indefinite amount of time. If you do not, the user interface will be blocked until the task is finished.

For example: if you trying to download a huge web page, if you task is run in the UI thread you will prevent the application from respond to other actions--such as pressing other buttons, zooming, pressing the back button--and your app will be frozen.

No one likes it when an app completely freezes, even if it is doing legitimate loading/calculating work. Additionally, if your app blocks the UI thread for more than 20 or so seconds, the Android Operating System will assume it is broken, and a force-close dialog will appear.

2. Using AsyncTasks

It is fairly easy to use AsyncTasks. You just need to extend the AsynTask class and choose three generic types to represent the parameters, the progress, and the result.

To demonstrate AsyncTasks we will create a simple task that just sleeps for 20 seconds to simulate an actual task. Listed below is the code that defines our task.

The only method that you are required to implement is the doInBackground method. Since this method will run in the background it is important not to update any UI elements in it.

There are a couple other methods that you can implement including onPreExecute and onPostExecute. These methods are self-explanatory about when they run. They run on the UI thread, so it is okay to update UI elements from within these methods.