編輯:Android 資訊
看到 HandlerThread,我們很快會聯想到 Handler。Android 中 Handler 的使用一般都在 UI 主線程中執行,因此在 Handler 接收訊息、處理訊息時,不能做一些很耗時的操作,否則將出現 ANR 錯誤。
Android 專門提供了 HandlerThread 類來解決這類問題。HandlerThread 讓一個執行緒專門處理 Handler 的訊息,依序從 Handler 佇列中獲取訊息逐個處理,保證安全、不會因混亂而引發異常。HandlerThread 繼承自 Thread,本質上就是個 Thread,與普通 Thread 的差別在於它有個 Looper 成員變數。
再來看看官方對它的說明:
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.
大致意思是:HandlerThread 可以建立一個帶有 Looper 的執行緒,該 Looper 物件可用於建立 Handler 類來進行調度。接下來看看 HandlerThread 的源碼:
package android.os; public class HandlerThread extends Thread { int mPriority; int mTid = -1; Looper mLooper; public HandlerThread(String name) { super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } protected void onLooperPrepared() { } @Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
執行緒 run() 方法中先呼叫 Looper.prepare() 初始化 Looper,最後呼叫 Looper.loop(),這樣我們就在該執行緒中建立好了 Looper(注意:Looper.loop() 預設是死循環)。
Handler 原理
要理解 Handler 的原理,理解以下幾個概念即可茅塞頓開:
想深入了解 Android 異步訊息處理機制,可參考 Looper、Handler、Message 三者關係的相關文章。
HandlerThread thread = newHandlerThread("handler_thread"); thread.start();//必須要調用start方法 final Handlerhandler = newHandler(thread.getLooper()){
其他 API:
//用於返回與該線程相關聯的Looper對象 thread.getLooper(); //獲得該線程的Id thread.getThreadId(); //結束當前的Looper 循環。 thread.quit(); //用於looper取出的消息處理 thread.run();
效果圖

在上圖中可以看到,當我點擊按鈕後,兩個藍色方塊變成了圖片。我在按鈕點擊事件中添加了兩個下載圖片的任務(模擬情況),並在加載完後替換控件的預設圖片。很明顯可以看到是有先後順序的——第一張圖片加載完後,第二張才會顯示。
public class MainActivity extends AppCompatActivity { private HandlerThread handlerThread; private ImageView imageView,imageView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { imageView= (ImageView) findViewById(R.id.imageView); imageView1= (ImageView) findViewById(R.id.imageView1); handlerThread = new HandlerThread("MainActivity"); handlerThread.start(); final Handler handler = new Handler(handlerThread.getLooper()); //點擊download開始進行下載 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.post(new MyRunable(1)); handler.post(new MyRunable(2)); } }); } class MyRunable implements Runnable { int pos; public MyRunable(int pos) { this.pos = pos; } @Override public void run() { //模擬耗時 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } if (pos == 1) { imageView.post(new Runnable() { @Override public void run() { imageView.setBackgroundResource(R.mipmap.ic_launcher); } }); } else { imageView1.post(new Runnable() { @Override public void run() { imageView1.setBackgroundResource(R.mipmap.ic_launcher); } }); } } } @Override protected void onDestroy() { super.onDestroy(); handlerThread.quit();//停止Looper的循環 } }
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.handlerthread.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/imageView" android:layout_width="100dp" android:layout_height="50dp" android:background="@android:color/holo_blue_dark" /> <ImageView android:id="@+id/imageView1" android:layout_width="100dp" android:layout_height="50dp" android:layout_marginLeft="10dp" android:background="@android:color/holo_blue_dark" /> </LinearLayout> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="downLoad" /> </LinearLayout>
源碼位址:https://github.com/Waylenw/AndroidBase
HandlerThread 適合只需在單一工作執行緒(非 UI 執行緒)搭配任務等待佇列的情境。優點是不會阻塞、減少效能消耗;缺點是不能同時處理多個任務,需排隊等待處理,處理效率較低。
感謝以下參考資料(更多詳細):
https://blog.csdn.net/lmj623565791/article/details/47079737
https://droidyue.com/blog/2015/11/08/make-use-of-handlerthread/?utm_source=tuicool&utm_medium=referral
用 Fragment 打造萬能的頁面切換框架
先回顧一下傳統的 Activity 跳轉方式:新建 Intent、塞入必要參數、調用 startActivity。如果需要返回結果,就改用 startActivityFo
22 款值得收藏的 Android Studio 高效插件精選
一、先認識一下 Android Studio 的插件生態 2013 年 5 月的 Google I/O 大會上,Android Studio 首次亮相。它脱胎於 Inte
Android Translucent System Bar 的最佳實踐
近幾天打算抽空總結 Android 一些系統 UI 的實踐用法,於是動手建了個庫 AndroidSystemUiTraining,邊撸代碼邊寫總結。今天開寫第一篇,對 T
Android N 值得關注的四個重大變化
Google 發布了 Android 的下一個版本 Android N 開發者預覽版。相比以往,這次的預覽來得更早一些,開發者可以在正式版發布前就動手試跑代碼、體驗新 A