1 page.title=Painless Threading 2 @jd:body 3 4 <p>This article discusses the threading model used by Android applications and how applications can ensure best UI performance by spawning worker threads to handle long-running operations, rather than handling them in the main thread. The article also explains the API that your application can use to interact with Android UI toolkit components running on the main thread and spawn managed worker threads. </p> 5 6 <h3>The UI thread</h3> 7 8 <p>When an application is launched, the system creates a thread called 9 "main" for the application. The main thread, also called the <em>UI 10 thread</em>, is very important because it is in charge of dispatching the 11 events to the appropriate widgets, including drawing events. 12 It is also the thread where your application interacts with running 13 components of the Android UI toolkit. </p> 14 15 <p>For instance, if you touch the a button on screen, the UI thread dispatches 16 the touch event to the widget, which in turn sets its pressed state and 17 posts an invalidate request to the event queue. The UI thread dequeues 18 the request and notifies the widget to redraw itself.</p> 19 20 <p>This single-thread model can yield poor performance unless your application 21 is implemented properly. Specifically, if everything is happening in a single 22 thread, performing long operations such as network access or database 23 queries on the UI thread will block the whole user interface. No event 24 can be dispatched, including drawing events, while the long operation 25 is underway. From the user's perspective, the application appears hung. 26 Even worse, if the UI thread is blocked for more than a few seconds 27 (about 5 seconds currently) the user is presented with the infamous "<a href="http://developer.android.com/guide/practices/design/responsiveness.html">application not responding</a>" (ANR) dialog.</p> 28 29 <p>If you want to see how bad this can look, write a simple application 30 with a button that invokes <code>Thread.sleep(2000)</code> in its 31 <a href="http://developer.android.com/reference/android/view/View.OnClickListener.html">OnClickListener</a>. 32 The button will remain in its pressed state for about 2 seconds before 33 going back to its normal state. When this happens, it is very easy for 34 the user to <em>perceive</em> the application as slow.</p> 35 36 <p>To summarize, it's vital to the responsiveness of your application's UI to 37 keep the UI thread unblocked. If you have long operations to perform, you should 38 make sure to do them in extra threads (<em>background</em> or <em>worker</em> 39 threads). </p> 40 41 <p>Here's an example of a click listener downloading an image over the 42 network and displaying it in an <a href="http://developer.android.com/reference/android/widget/ImageView.html">ImageView</a>:</p> 43 44 <pre class="prettyprint">public void onClick(View v) { 45 new Thread(new Runnable() { 46 public void run() { 47 Bitmap b = loadImageFromNetwork(); 48 mImageView.setImageBitmap(b); 49 } 50 }).start(); 51 }</pre> 52 53 <p>At first, this code seems to be a good solution to your problem, as it does 54 not block the UI thread. Unfortunately, it violates the single-threaded model 55 for the UI: the Android UI toolkit is <em>not thread-safe</em> and must always 56 be manipulated on the UI thread. In this piece of code above, the 57 <code>ImageView</code> is manipulated on a worker thread, which can cause really 58 weird problems. Tracking down and fixing such bugs can be difficult and 59 time-consuming.</p> 60 61 <p>Android offers several ways to access the UI 62 thread from other threads. You may already be familiar with some of 63 them but here is a comprehensive list:</p> 64 65 <ul> 66 <li>{@link android.app.Activity#runOnUiThread(java.lang.Runnable) Activity.runOnUiThread(Runnable)}</li> 67 <li>{@link android.view.View#post(java.lang.Runnable) View.post(Runnable)}</li> 68 <li>{@link android.view.View#postDelayed(java.lang.Runnable, long) View.postDelayed(Runnable, long)}</li> 69 <li>{@link android.os.Handler}</li> 70 </ul> 71 72 <p>You can use any of these classes and methods to correct the previous code example:</p> 73 74 <pre class="prettyprint">public void onClick(View v) { 75 new Thread(new Runnable() { 76 public void run() { 77 final Bitmap b = loadImageFromNetwork(); 78 mImageView.post(new Runnable() { 79 public void run() { 80 mImageView.setImageBitmap(b); 81 } 82 }); 83 } 84 }).start(); 85 }</pre> 86 87 <p>Unfortunately, 88 these classes and methods could also tend to make your code more complicated 89 and more difficult to read. It becomes even worse when your implement 90 complex operations that require frequent UI updates. </p> 91 92 <p>To remedy this problem, Android 1.5 and later platforms offer a utility class 93 called {@link android.os.AsyncTask}, that simplifies the creation of 94 long-running tasks that need to communicate with the user interface.</p> 95 96 <p>An <code>AsyncTask</code> equivalent is also available for applications that 97 will run on Android 1.0 and 1.1. The name of the class is <a 98 href="http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/ 99 curiouscreature/android/shelves/util/UserTask.java">UserTask</a>. It offers the 100 exact same API and all you have to do is copy its source code in your 101 application.</p> 102 103 <p>The goal of <code>AsyncTask</code> is to take care of thread management for 104 you. Our previous example can easily be rewritten with 105 <code>AsyncTask</code>:</p> 106 107 <pre class="prettyprint">public void onClick(View v) { 108 new DownloadImageTask().execute("http://example.com/image.png"); 109 } 110 111 private class DownloadImageTask extends AsyncTask<string, void,="" bitmap=""> { 112 protected Bitmap doInBackground(String... urls) { 113 return loadImageFromNetwork(urls[0]); 114 } 115 116 protected void onPostExecute(Bitmap result) { 117 mImageView.setImageBitmap(result); 118 } 119 }</pre> 120 121 <p>As you can see, <code>AsyncTask</code> <em>must</em> be used by subclassing 122 it. It is also very important to remember that an <code>AsyncTask</code> 123 instance has to be created on the UI thread and can be executed only once. You 124 can read the <a 125 href="http://developer.android.com/reference/android/os/AsyncTask.html"> 126 AsyncTask documentation</a> for a full understanding on how to use this class, 127 but here is a quick overview of how it works:</p> 128 129 <ul> 130 <li>You can specify the type, using generics, of the parameters, the progress values and the final value of the task</li> 131 <li>The method <a href="http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground%28Params...%29">doInBackground()</a> executes automatically on a worker thread</li> 132 <li><a href="http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute%28%29">onPreExecute()</a>, <a href="http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute%28Result%29">onPostExecute()</a> and <a href="http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate%28Progress...%29">onProgressUpdate()</a> are all invoked on the UI thread</li> 133 <li>The value returned by <a href="http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground%28Params...%29">doInBackground()</a> is sent to <a href="http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute%28Result%29">onPostExecute()</a></li> 134 <li>You can call <a href="http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress%28Progress...%29">publishProgress()</a> at anytime in <a href="http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground%28Params...%29">doInBackground()</a> to execute <a href="http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate%28Progress...%29">onProgressUpdate()</a> on the UI thread</li><li>You can cancel the task at any time, from any thread</li> 135 </ul> 136 137 <p>In addition to the official documentation, you can read several complex examples in the source code of Shelves (<a href="http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/activity/ShelvesActivity.java">ShelvesActivity.java</a> and <a href="http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/activity/AddBookActivity.java">AddBookActivity.java</a>) and Photostream (<a href="http://code.google.com/p/apps-for-android/source/browse/trunk/Photostream/src/com/google/android/photostream/LoginActivity.java">LoginActivity.java</a>, <a href="http://code.google.com/p/apps-for-android/source/browse/trunk/Photostream/src/com/google/android/photostream/PhotostreamActivity.java">PhotostreamActivity.java</a> and <a href="http://code.google.com/p/apps-for-android/source/browse/trunk/Photostream/src/com/google/android/photostream/ViewPhotoActivity.java">ViewPhotoActivity.java</a>). We highly recommend reading the source code of <a href="http://code.google.com/p/shelves/">Shelves</a> to see how to persist tasks across configuration changes and how to cancel them properly when the activity is destroyed.</p> 138 139 <p>Regardless of whether or not you use <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask</a>, 140 always remember these two rules about the single thread model: </p> 141 142 <ol> 143 <li>Do not block the UI thread, and 144 <li>Make sure that you access the Android UI toolkit <em>only</em> on the UI thread. 145 </ol> 146 147 <p><code>AsyncTask</code> just makes it easier to do both of these things.</p> 148