Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入 Android 異步消息機制:Handler、Looper 與 MessageQueue 的協作原理

編輯:關於 Android 程式設計

前言:

(1)在 Android 中,線程間的消息通信靠 Handler 來完成。之所以離不開它,是因為 UI 操作只能在主線程進行,而網絡請求等耗時任務又不能阻塞主線程,於是我們把耗時操作放到子線程,再借助 Handler 把結果切換回主線程更新界面:

 private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } }).start(); }

(2)Handler 的運行離不開 Looper 和 MessageQueue 的支持,只不過新建 Activity 時系統已替我們準備好了主線程的 Looper 與 MessageQueue。若要在子線程使用 Handler,就必須手動調用 Looper.prepare() 和 Looper.loop():

 class MyThread implements Runnable{ private Handler handler; @Override public void run() { Looper.prepare(); handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; Looper.loop(); } }

(3)整體流程可以這樣串起來:先通過 Looper.prepare() 把 Looper 綁定到當前線程,創建 Looper 時順帶創建了一個 MessageQueue;接著 new 一個 Handler,它會自動關聯到當前線程的 Looper 與 MessageQueue;調用 sendMessage() 時,Message 被插入 MessageQueue;最後 Looper.loop() 不停遍歷隊列取出 Message,交給 msg.target 處理——這個 target 正是當初的 Handler(在 sendMessage 過程中完成賦值)。target 再調用 dispatchMessage(),最終走到我們需要重寫的 handleMessage()。下面逐個方法拆解源碼。

1. Looper.prepare()

它的作用是創建 Looper 並綁定到當前線程,同時創建 MessageQueue。綁定線程靠的是 ThreadLocal——它能在不同線程間互不干擾地存儲和提供數據。

源碼第 78 行 sThreadLocal.set(new Looper(quitAllowed)) 把新建的 Looper 存進 ThreadLocal,而在此之前會先判斷 ThreadLocal 裡是否已有 Looper,不為 null 就拋異常,以此保證「一個線程只能有一個 Looper」。

 51 52 public final class More ...Looper { 53 private static final String TAG = "Looper"; 54 55 // sThreadLocal.get() will return null unless you've called prepare(). 56 static final ThreadLocal sThreadLocal = new ThreadLocal(); 57 private static Looper sMainLooper; // guarded by Looper.class 58 59 final MessageQueue mQueue; 60 final Thread mThread; 61 62 private Printer mLogging;
 70 public static void More ...prepare() { 71 prepare(true); 72 } 
 74 private static void More ...prepare(boolean quitAllowed) { 75 if (sThreadLocal.get() != null) { 76 throw new RuntimeException("Only one Looper may be created per thread"); 77 } 78 sThreadLocal.set(new Looper(quitAllowed)); 79 }

再看 Looper 的構造方法,新建 Looper 時會順手創建 MessageQueue,從源頭上確保了「一個線程一個 Looper、一個 MessageQueue」:

 private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mRun = true; mThread = Thread.currentThread(); } 

2. 新建 Handler 對象

Handler 構造方法第 198 行 mLooper = Looper.myLooper() 拿到了當前線程的 Looper,而 myLooper() 本質上就是 return sThreadLocal.get(),取回的正是第 78 行存進去的那個 Looper。接著第 203 行 mQueue = mLooper.mQueue 關聯到 MessageQueue。這樣,Handler 便通過 ThreadLocal 與 Looper、MessageQueue 掛上了鉤。

 187 188 public More ...Handler(Callback callback, boolean async) { 189 if (FIND_POTENTIAL_LEAKS) { 190 final Class klass = getClass(); 191 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 192 (klass.getModifiers() & Modifier.STATIC) == 0) { 193 Log.w(TAG, "The following Handler class should be static or leaks might occur: " + 194 klass.getCanonicalName()); 195 } 196 } 197 198 mLooper = Looper.myLooper(); 199 if (mLooper == null) { 200 throw new RuntimeException( 201 "Can't create handler inside thread that has not called Looper.prepare()"); 202 } 203 mQueue = mLooper.mQueue; 204 mCallback = callback; 205 mAsynchronous = async; 206 }
 160 public static Looper More ...myLooper() { 161 return sThreadLocal.get(); 162 } 

3. handler.sendMessage(message)

無論是 sendMessage 還是 sendEmptyMessage,最終都會走到 enqueueMessage。在這個方法裡,queue.enqueueMessage(msg, uptimeMillis)(631 行)把 message 塞進 MessageQueue,而 msg.target = this(627 行)把當前 Handler 賦值給了 msg.target。當 Looper 遍歷隊列取出 Message,就會交給 msg.target,也就是交給 Handler 處理了。

 505 public final boolean More ...sendMessage(Message msg) { 506 { return sendMessageDelayed(msg, 0); 508 }
 516 517 public final boolean More ...sendEmptyMessage(int what) { 518 { return sendEmptyMessageDelayed(what, 0); 520 }
 531 public final boolean More ...sendEmptyMessageDelayed(int what, long delayMillis) { 532 Message msg = Message.obtain(); 533 msg.what = what; 534 return sendMessageDelayed(msg, delayMillis); 535 }
 592 public boolean More ...sendMessageAtTime(Message msg, long uptimeMillis) { 593 MessageQueue queue = mQueue; 594 if (queue == null) { 595 RuntimeException e = new RuntimeException( 596 this + " sendMessageAtTime() called with no mQueue"); 597 Log.w("Looper", e.getMessage(), e); 598 return false; 599 } 600 return enqueueMessage(queue, msg, uptimeMillis); 601 }
 626 private boolean More ...enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { 627 msg.target = this; 628 if (mAsynchronous) { 629 msg.setAsynchronous(true); 630 } 631 return queue.enqueueMessage(msg, uptimeMillis); 632 }

4. Looper.loop()

當 MessageQueue 裡有消息時,loop 會不斷遍歷取出 Message 交給 Handler;沒有消息時則進入阻塞狀態,等待新消息喚醒。

 public static void More ...loop() { 110 final Looper me = myLooper(); 111 if (me == null) { 112 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 113 } 114 final MessageQueue queue = me.mQueue; 115 116 // Make sure the identity of this thread is that of the local process, 117 // and keep track of what that identity token actually is. 118 Binder.clearCallingIdentity(); 119 final long ident = Binder.clearCallingIdentity(); 120 121 for (;;) { 122 Message msg = queue.next(); // might block 123 if (msg == null) { 124 // No message indicates that the message queue is quitting. 125 return; 126 } 127 128 // This must be in a local variable, in case a UI event sets the logger 129 Printer logging = me.mLogging; 130 if (logging != null) { 131 logging.println(">>>>> Dispatching to " + msg.target + " " 132 + msg.callback + ": " + msg.what); 133 } 134 135 msg.target.dispatchMessage(msg); 136 137 if (logging != null) { 138 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); 139 } 140 141 // Make sure that during the course of dispatching the 142 // identity of the thread wasn't corrupted. 143 final long newIdent = Binder.clearCallingIdentity(); 144 if (ident != newIdent) { 145 Log.wtf(TAG, "Thread identity changed from 0x" 146 + Long.toHexString(ident) + " to 0x" 147 + Long.toHexString(newIdent) + " while dispatching to " 148 + msg.target.getClass().getName() + " " 149 + msg.callback + " what=" + msg.what); 150 } 151 152 msg.recycleUnchecked(); 153 } 154 }

第 110–114 行取出 Looper 和 MessageQueue,Looper 為空則拋異常;第 121–153 行是無限循環遍歷;第 122 行 queue.next() 取消息,取不到就阻塞;第 135 行 msg.target.dispatchMessage(msg) 把消息交給 Handler 分發。

 93 public void More ...dispatchMessage(Message msg) { 94 if (msg.callback != null) { 95 handleCallback(msg); 96 } else { 97 if (mCallback != null) { 98 if (mCallback.handleMessage(msg)) { 99 return; 100 } 101 } 102 handleMessage(msg); 103 } 104 }

若 msg.callback 和 mCallback 都為 null,就走第 102 行的 handleMessage(msg)——這正是我們需要重寫來處理消息的方法。若 msg.callback 不為 null,則走第 95 行 handleCallback(msg),其實現(739 行)就是 message.callback.run(),也就是說 callback 本質上就是一個 Runnable,我們在 handler.post(runnable) 時設置了它。

 private static void More ...handleCallback(Message message) { 739 message.callback.run(); 740 }

再看 post 方法,它同樣調用了 sendMessageDelayed(326 行),與 sendMessage、sendEmptyMessage 殊途同歸。而 getPostMessage 的實現,就是創建一個空 Message 並把 Runnable 賦給 m.callback(727 行)。於是 handler.post(runnable) 也完成了「發送—傳遞—處理」的閉環,只不過最終是在 message.callback.run() 裡處理消息,所以我們要重寫的是 run 方法。

 324 public final boolean More ...post(Runnable r) { 325 { return sendMessageDelayed(getPostMessage(r), 0); 327 }
 725 private static Message More ...getPostMessage(Runnable r) { 726 Message m = Message.obtain(); 727 m.callback = r; 728 return m; 729 }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved