Android AsyncTask Example

Today I was working on a loading screen for an Android app. The purpose of the loading screen is to report to the user which boot up processes were happening as well as provide a nice looking intro screen for the app. The U.I. layer of an Android app runs in a single thread. You can think of a thread as a stack of function calls. Each function in the list executes only after the one before it has completed. This is a very simplistic view of a thread but for the sake of this post it will work. With multiple processor intensive functions stacked up the U.I. layer can become inactive and appear to hang while waiting for the stack to finish. This problem can be solved by splitting up the processes into separate threads. By doing so your U.I. layer can update concurrent with the other more intensive processes.

The Android operating system provides a couple of solutions to this problem. The solution I implemented for the loading screen was a class called AsyncTask. It’s a wrapper for a threaded operation that provides some really convenient callbacks for updating progress information and handling task completion.

ยป Download complete example code here

Let’s look at how to go about instantiating an AsyncTask. First off, you must sub-class AsyncTask and provide three parameters. These three parameters indicate the types of objects that are passed to three callbacks you can override in your sub-class. You can set these parameter to any type that suits your application. In the following example I am using a Context object and two Integer objects.

protected class InitTask extends AsyncTask<Context, Integer, Integer>
In the line above we define our sub-class and the three parameters that will be passed to the callbacks. The callbacks look like this:

doInBackground()

@Override
protected Integer doInBackground( Context... params )  {
     return super.doInBackground( params )
}

Anything processed in this method is handled in a sperate thread. Note that the data type of the return value is an Integer and corresponds to the type third parameter in the class definition. This value returned from this method is passed to the onPostExecute() method when this thread completes.

onProgressUpdate()

@Override
protected void onProgressUpdate(Integer... values)  {
     super.onProgressUpdate(values);
}

Report progress of async operations via this method. Note the param with datatype Integer. This corresponds to the second parameter in the class definition. This callback can be triggered from within the body of the doInBackground() method by calling publishProgress()

onPostExecute()

@Override
protected void onPostExecute( Integer result )  {
      super.onPostExecute(result);
}

This method is called when the thread has completed successfully. Note that the datatype passed to this parameter matches the third parameter in the method definition.

The AsyncTask class provides to other helpful callback methods onCancelled() which handles the cancellation of the thread and onPreExecute() which is called just before the thread calls doInBackground().

A complete example project using AsyncTask is available from the makemachine code repository.

Posted in Android | 19 Comments

19 Responses to Android AsyncTask Example

  1. Chuck Chapowski says:

    Excellent article, very helpful & explained some concepts I’ve just met for the 1st time – well done :-)

  2. Jeremy says:

    Glad to hear it!

  3. sohan badaya says:

    Really nice article. Thanks!!!

  4. jimmcwin says:

    Hi jeremy,

    Thanks for good works posting this article. I am new in Android and Java. I am trying to understand the Android gragphics system, specially touch screen interface with UI and frame buffer. Do you have any good references where I can look into.

    Thanks,

    Jim

  5. Musa says:

    This explanation is even better than the api doc!! Jeremy u’re a God send! Thanks

  6. Pingback: Books, tutorials and webbook | Biocram's Blog

  7. Pingback: skill set « jamandroid

  8. Michael says:

    Very well written article…and loved your coding style..Thanks man

  9. J says:

    Thanks for taking the time to write this. It has really helped me have a clearer understanding of how to utlise async. If you had an advert banner I’d click it out of thanks.

  10. Jeremy says:

    Good to hear you found it useful! Kudos from readers is a much better motivator than ad revenue :)

  11. Baz says:

    Many thanks for the clear description of the three callbacks and the params passed. Your work just highlights how bad the Android api docs are! B.

  12. Sushil Pant says:

    This is awesome!!! very understandable post. Thanks for sharing with us. you may check this helpful link…
    http://mindstick.com/Articles/c25f0596-db32-4a79-bda4-38535f3b8dc0/?Using%20AsyncTask%20in%20Android%20Application

    It is helped me lot to complete my task.

  13. harvey says:

    Excellent article,awesome!!!

  14. Nitin says:

    Gr8 example…simple, yet complete, and equally gud source code…

  15. shahul says:

    good example

  16. L says:

    You sir are a hero. I’ve been banging my head over 20 different pages including the api docs and stackoverflow. I came here and “AsyncTask” makes total sense to me now. They should have had you write the android api docs. You’d be rich and we’d be happy

  17. sandeep says:

    nice tuttorial

  18. Mayaa says:

    Really Nice post… Thanku so much.. Even thishttp://androidtechstuffs.blogspot.in/2013/01/why-and-how-to-use-asynctask.html is also helpful. have a look..

  19. seth says:

    very well explained.keep up the good work.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>