Painless threading

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.

原文地址:
Painless threading

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谱邪,一起剝皮案震驚了整個濱河市八堡,隨后出現(xiàn)的幾起案子索赏,更是在濱河造成了極大的恐慌吼鳞,老刑警劉巖喊废,帶你破解...
    沈念sama閱讀 211,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绅这,死亡現(xiàn)場離奇詭異糯累,居然都是意外死亡算利,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評論 3 385
  • 文/潘曉璐 我一進店門泳姐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來效拭,“玉大人,你說我怎么就攤上這事胖秒《谢迹” “怎么了?”我有些...
    開封第一講書人閱讀 157,435評論 0 348
  • 文/不壞的土叔 我叫張陵阎肝,是天一觀的道長挤渔。 經(jīng)常有香客問我,道長盗痒,這世上最難降的妖魔是什么蚂蕴? 我笑而不...
    開封第一講書人閱讀 56,509評論 1 284
  • 正文 為了忘掉前任低散,我火速辦了婚禮,結(jié)果婚禮上骡楼,老公的妹妹穿的比我還像新娘熔号。我一直安慰自己,他們只是感情好鸟整,可當(dāng)我...
    茶點故事閱讀 65,611評論 6 386
  • 文/花漫 我一把揭開白布引镊。 她就那樣靜靜地躺著,像睡著了一般篮条。 火紅的嫁衣襯著肌膚如雪弟头。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,837評論 1 290
  • 那天涉茧,我揣著相機與錄音赴恨,去河邊找鬼。 笑死伴栓,一個胖子當(dāng)著我的面吹牛伦连,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播钳垮,決...
    沈念sama閱讀 38,987評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼惑淳,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了饺窿?” 一聲冷哼從身側(cè)響起歧焦,我...
    開封第一講書人閱讀 37,730評論 0 267
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肚医,沒想到半個月后绢馍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,194評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡忍宋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,525評論 2 327
  • 正文 我和宋清朗相戀三年痕貌,在試婚紗的時候發(fā)現(xiàn)自己被綠了风罩。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片糠排。...
    茶點故事閱讀 38,664評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖超升,靈堂內(nèi)的尸體忽然破棺而出入宦,到底是詐尸還是另有隱情,我是刑警寧澤室琢,帶...
    沈念sama閱讀 34,334評論 4 330
  • 正文 年R本政府宣布乾闰,位于F島的核電站,受9級特大地震影響盈滴,放射性物質(zhì)發(fā)生泄漏涯肩。R本人自食惡果不足惜轿钠,卻給世界環(huán)境...
    茶點故事閱讀 39,944評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望病苗。 院中可真熱鬧疗垛,春花似錦、人聲如沸硫朦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,764評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽咬展。三九已至泽裳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間破婆,已是汗流浹背涮总。 一陣腳步聲響...
    開封第一講書人閱讀 31,997評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留祷舀,地道東北人妹卿。 一個月前我還...
    沈念sama閱讀 46,389評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像蔑鹦,于是被迫代替她去往敵國和親夺克。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,554評論 2 349

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,437評論 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,444評論 5 6
  • 最近運營商開始推廣200M寬帶嚎朽,但原本PDCN固件中7620很多路由都是100M網(wǎng)絡(luò)端口的铺纽,導(dǎo)致無法正常發(fā)揮寬帶的...
    bigANDY閱讀 3,675評論 4 2
  • 要真誠,要真誠哟忍, 我反復(fù)對自己說狡门。 對功名利祿,對一棵小草锅很, 都要真誠其馏。 對天邊的一縷云彩, 對母親溫柔的目光爆安, ...
    戀曲1991閱讀 333評論 0 0
  • 《不懂帶人叛复,你就自己干到死》書中分享了幾個關(guān)于溝通的方法,剛好自己在工作中也嘗試運用扔仓,初見成效褐奥。所以結(jié)合一些日常的...
    玲珍閱讀 465評論 0 1