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

Android 訊息機制深入解析:Handler、Looper 與 MessageQueue

編輯:關於 Android 程式設計

一、簡介

Android 的訊息機制主要指 Handler 的運作原理。通俗地說,就是透過 Handler 把子執行緒的 Message 放進主執行緒的 MessageQueue,再由主執行緒取出處理。

二、四個關鍵角色

1、Message:訊息的載體。

2、MessageQueue:訊息佇列。

3、Looper:訊息循環,負責不停取出訊息。

4、Handler:訊息處理者,決定拿到的訊息要怎麼做。

平常我們打交道的只有 Handler 與 Message,下面從原始碼把整條鏈走一遍。

三、原始碼解析

一般我們會這樣送訊息:

xxHandler.sendEmptyMessage(xxx);

寫法還有其他幾種,但一路追下去會發現它們最終都收斂到同一個方法:

 public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }

但這还不是終點。最後那句 enqueueMessage 顧名思義是「插入一條訊息」,問題是插去哪裡?

 boolean enqueueMessage(Message msg, long when) { if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don't have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; } 

於是又冒出一個新角色:MessageQueue。雖然我們習慣叫它「佇列」,但從原始碼看,它其實是單向鏈結串列,對它的操作主要就是插入與讀取。上面程式碼中段那段邏輯,就是資料結構課本裡「插入到鏈結串列適當位置」的實作(依 when 排序,而非單純接在尾端)。

也就是說,send 系列方法的本質是往 MessageQueue 裡插入一條訊息。那要怎麼把它取出來處理?這就輪到 Looper 上場。

Looper:訊息循環

Looper 的角色是持續從 MessageQueue 查看有沒有新訊息,有就立刻交給對應的 Handler 處理,沒有就阻塞等待。先看它的建構子:

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

它把當前執行緒存了起來。新執行緒中建立 Looper 有兩個關鍵方法:

 new Thread(){ public void run(){ Looper.prepare(); Handler handler = new Handler(); Looper.loop(); } }.start();

prepare() 的原始碼:

 private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }

這裡出現了 ThreadLocal。它是執行緒內部的資料儲存類別:透過它存進去的資料,只有該執行緒能讀取,其他執行緒拿到的是各自的值。用個小例子看:

 private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();// mBooleanThreadLocal.set(true); Log.d(TAH,"Threadmain"+mBooleanThreadLocal.get()); new Thread("Thread#1"){ public void run(){ mBooleanThreadLocal.set(false); Log.d(TAH,"Thread#1"+mBooleanThreadLocal.get()); }; }.start(); new Thread("Thread#2"){ public void run(){ Log.d(TAH,"Thread#2"+mBooleanThreadLocal.get()); }; }.start(); 

執行後會發現每個執行緒印出的值都不同,即使它們存取的是同一個 ThreadLocal 物件。這也是為什麼「每個執行緒只能有一個 Looper」——它就被存在 ThreadLocal 裡。

再看 loop():

 public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }

先取得當前執行緒的 Looper,取不到就拋異常,接著拿到 MessageQueue 並進入無窮迴圈。這裡要補充 MessageQueue.next():

 Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } } 

它會遍歷佇列尋找可處理的 msg;若沒有,就把 nextPollTimeoutMillis 設為 -1 並透過 nativePollOnce 阻塞在這裡,等待 enqueueMessage 中的 nativeWake 喚醒。更深一層涉及 native 程式碼,有興趣可以往下研究。一句話總結:next() 有訊息時回傳該訊息,沒有就卡在那裡等。

回到 loop(),關鍵是這一行:

msg.target.dispatchMessage(msg);

 public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }

msg.target 就是送出這條訊息的 Handler。它先交給 dispatchMessage,依序嘗試 msg 上的 Runnable callback、Handler 設定的 mCallback,最後才落到我們最熟悉的 handleMessage(msg)。這也解釋了為什麼覆寫 handleMessage 就能攔到訊息。

四、總結

整條鏈是這樣串起來的:Handler.sendMessage 把 Message 依執行時間排入 MessageQueue(單向鏈結串列),Looper.loop 在無窮迴圈中呼叫 queue.next() 取件,取到後交給 msg.target.dispatchMessage,最終進到 handleMessage 由我們處理。主執行緒之所以能保持非同步,正是因為 Looper 在沒事時會阻塞在 nativePollOnce,而不是空轉耗 CPU。訊息機制往下還有 native 層的管道與 Barrier、IdleHandler 等機制,有興趣可以繼續深入。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved