Android-Developers

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 6 May 2009

Painless threading

Posted on 09:30 by Unknown

Whenever you first start an Android application, a thread called "main" is automatically created. The main thread, also called the UI thread, is very important because it is in charge of dispatching the events to the appropriate widgets and this includes the drawing events. It is also the thread you interact with Android widgets on. For instance, if you touch the a button on screen, the UI thread dispatches the touch event to the widget which in turn sets its pressed state and posts an invalidate request to the event queue. The UI thread dequeues the request and notifies the widget to redraw itself.

This single thread model can yield poor performance in Android applications that do not consider the implications. Since everything happens on a single thread performing long operations, like network access or database queries, on this thread will block the whole user interface. No event can be dispatched, including drawing events, while the long operation is underway. From the user's perspective, the application appears hung. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog.

If you want to see how bad this can look, write a simple application with a button that invokes Thread.sleep(2000) in its OnClickListener. The button will remain in its pressed state for about 2 seconds before going back to its normal state. When this happens, it is very easy for the user to perceive the application as slow.

Now that you know you must avoid lengthy operations on the UI thread, you will probably use extra threads (background or worker threads) to perform these operations, and rightly so. Let's take the example of a click listener downloading an image over the network and displaying it in an ImageView:

public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork();
mImageView.setImageBitmap(b);
}
}).start();
}

At first, this code seems to be a good solution to your problem, as it does not block the UI thread. Unfortunately, it violates the single thread model: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In this piece of code, the ImageView is manipulated on a worker thread, which can cause really weird problems. Tracking down and fixing such bugs can be difficult and time-consuming.

Android offers several ways to access the UI thread from other threads. You may already be familiar with some of them but here is a comprehensive list:

  • Activity.runOnUiThread(Runnable)
  • View.post(Runnable)
  • View.postDelayed(Runnable, long)
  • Handler

Any of these classes and methods could be used to correct our previous code example:

public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap b = loadImageFromNetwork();
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(b);
}
});
}
}).start();
}

Unfortunately, these classes and methods also tend to make your code more complicated and more difficult to read. It becomes even worse when your implement complex operations that require frequent UI updates. To remedy this problem, Android 1.5 offers a new utility class, called AsyncTask, that simplifies the creation of long-running tasks that need to communicate with the user interface.

AsyncTask is also available for Android 1.0 and 1.1 under the name UserTask. It offers the exact same API and all you have to do is copy its source code in your application.

The goal of AsyncTask is to take care of thread management for you. Our previous example can easily be rewritten with AsyncTask:

public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask {
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}

protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}

As you can see, AsyncTask must be used by subclassing it. It is also very important to remember that an AsyncTask instance has to be created on the UI thread and can be executed only once. You can read the AsyncTask documentation for a full understanding on how to use this class, but here is a quick overview of how it works:

  • You can specify the type, using generics, of the parameters, the progress values and the final value of the task
  • The method doInBackground() executes automatically on a worker thread
  • onPreExecute(), onPostExecute() and onProgressUpdate() are all invoked on the UI thread
  • The value returned by doInBackground() is sent to onPostExecute()
  • You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread
  • You can cancel the task at any time, from any thread

In addition to the official documentation, you can read several complex examples in the source code of Shelves (ShelvesActivity.java and AddBookActivity.java) and Photostream (LoginActivity.java, PhotostreamActivity.java and ViewPhotoActivity.java). I highly recommend reading the source code of Shelves to see how to persist tasks across configuration changes and how to cancel them properly when the activity is destroyed.

Regardless of whether or not you use AsyncTask, always remember these two rules about the single thread model: do not block the UI thread and make sure the Android UI toolkit is only accessed on the UI thread. AsyncTask just makes it easier to do both of these things.

If you want to learn more cool techniques, come join us at Google I/O. Members of the Android team will be there to give a series of in-depth technical sessions and answer all your questions.

Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in Android 1.5, How-to, User Interface | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Bring Your Apps into the Classroom, with Google Play for Education
    Posted by Shazia Makhdumi, Head of Strategic EDU Partnerships, Google Play team Google Play for Education has officially launched . It’s an ...
  • A Faster Emulator with Better Hardware Support
    [This post is by Xavier Ducrohet and Reto Meier of the Android engineering team. — Tim Bray.] The Android emulator is a key tool for Android...
  • Powering Chrome to Phone with Android Cloud to Device Messaging
    [This post is by Dave Burke, who's an Engineering Manager 80% of the time. — Tim Bray] Android Cloud to Device Messaging (C2DM) was lau...
  • Android 1.5 is here!
    I've got some good news today: the Android 1.5 SDK, release 1 is ready! Grab it from the download page . For an overview of the new Andr...
  • Memory Analysis for Android Applications
    [This post is by Patrick Dubroy, an Android engineer who writes about programming, usability, and interaction on his personal blog . — Tim B...
  • Preview of Google TV Add-on for the Android SDK
    [This post is by Ambarish Kenghe, who’s a Product Manager for Google TV — Tim Bray] At Google I/O , we announced that Android Market is comi...
  • Android SDK Tools, Revision 20
    [This post is by Xavier Ducrohet , Tech Lead for the Android developer tools] Along with the preview of the Android 4.1 (Jelly Bean) platfo...
  • RenderScript Intrinsics
    Posted by R. Jason Sams , Android RenderScript Tech Lead RenderScript has a very powerful ability called Intrinsics . Intrinsics are built-...
  • In-App Billing on Android Market: Ready for Testing
    [This post is by Eric Chu, Android Developer Ecosystem. —Dirk Dougherty] Back in January we announced our plan to introduce Android Market ...
  • Twitter for Android: A closer look at Android’s evolving UI patterns
    [This post is by Chris Nesladek, Interaction Designer, Richard Fulcher, Interaction Designer, and Virgil Dobjanschi, Software Engineer — Ti...

Categories

  • accessibility
  • Action Bar
  • Administration
  • Android
  • Android 1.5
  • Android 1.6
  • Android 2.0
  • Android 2.1
  • Android 2.2
  • Android 2.3
  • Android 2.3.3
  • Android 3.0
  • Android 3.2
  • Android 4.0
  • Android 4.2
  • Android 4.3
  • Android 4.4
  • Android Design
  • Android Developer Challenge
  • Android Developer Phone
  • Android Market
  • Android SDK
  • Android Studio
  • Animation and Graphics
  • Announcements
  • App Components
  • App Resources
  • Apps
  • Audio
  • Authentication
  • Best Practices
  • Boston
  • Code Day
  • Connectivity
  • Content Provider
  • Cool Stuff
  • Dashboard
  • Daydream
  • Debugging
  • Developer Console
  • Developer Days
  • Developer Labs
  • Developer profiles
  • Developer Story
  • Education
  • Games
  • GCM
  • Gestures
  • Google Analytics
  • Google Cloud Messaging
  • Google Cloud Platform
  • Google I/O
  • Google Play
  • Google Play game services
  • Google Play services
  • Google Services
  • Google Wallet
  • Google+
  • Guidelines
  • How-to
  • Image Processing
  • IME
  • In-app Billing
  • Input methods
  • Intents
  • io2010
  • IO2013
  • JNI
  • Layout
  • Localization
  • Location
  • Location and Sensors
  • London
  • Maps
  • Media and Camera
  • Mountain View
  • Munich
  • NDK
  • Open source
  • OpenGL ES
  • Optimization
  • Performance
  • Photo Sphere
  • Promo Graphics
  • Quality
  • Quick Search Box
  • Renderscript
  • Resources
  • RTL
  • Sample code
  • SDK Tools
  • SDK updates
  • Security
  • Sensors
  • Speech Input
  • Support Library
  • Survey
  • Tablets
  • Tel Aviv
  • Telephony
  • Testing
  • Text and Input
  • Text-to-Speech
  • Tools
  • Touch
  • User Interface
  • User Support
  • WebView
  • Widgets

Blog Archive

  • ►  2013 (45)
    • ►  November (2)
    • ►  October (7)
    • ►  September (2)
    • ►  August (5)
    • ►  July (5)
    • ►  June (4)
    • ►  May (9)
    • ►  April (3)
    • ►  March (2)
    • ►  February (3)
    • ►  January (3)
  • ►  2012 (43)
    • ►  December (5)
    • ►  November (3)
    • ►  October (3)
    • ►  September (1)
    • ►  August (1)
    • ►  July (2)
    • ►  June (5)
    • ►  May (1)
    • ►  April (5)
    • ►  March (6)
    • ►  February (5)
    • ►  January (6)
  • ►  2011 (67)
    • ►  December (7)
    • ►  November (7)
    • ►  October (5)
    • ►  September (5)
    • ►  August (3)
    • ►  July (7)
    • ►  June (3)
    • ►  May (5)
    • ►  April (6)
    • ►  March (8)
    • ►  February (7)
    • ►  January (4)
  • ►  2010 (72)
    • ►  December (8)
    • ►  November (3)
    • ►  October (4)
    • ►  September (8)
    • ►  August (6)
    • ►  July (9)
    • ►  June (11)
    • ►  May (11)
    • ►  April (2)
    • ►  March (3)
    • ►  February (2)
    • ►  January (5)
  • ▼  2009 (63)
    • ►  December (7)
    • ►  November (5)
    • ►  October (5)
    • ►  September (8)
    • ►  August (2)
    • ►  July (1)
    • ►  June (2)
    • ▼  May (5)
      • Calling all developers for Android Developer Chall...
      • Android Icon Guidelines
      • Lightning talks at Google I/O
      • Painless threading
      • Drawable mutations
    • ►  April (12)
    • ►  March (5)
    • ►  February (8)
    • ►  January (3)
  • ►  2008 (40)
    • ►  December (3)
    • ►  November (1)
    • ►  October (4)
    • ►  September (6)
    • ►  August (4)
    • ►  June (1)
    • ►  May (5)
    • ►  April (4)
    • ►  March (5)
    • ►  February (2)
    • ►  January (5)
  • ►  2007 (8)
    • ►  December (3)
    • ►  November (5)
Powered by Blogger.

About Me

Unknown
View my complete profile