編輯:關於 Android 程式設計
Android 的消息機制主要指 Handler 的運行機制,而 Handler 的運行需要底層 MessageQueue 和 Looper 的支撐。
MessageQueue
消息隊列,以隊列(實為單鏈表結構)的形式對外提供插入和刪除的能力。
Looper
以無限循環的形式不斷從 MessageQueue 中獲取消息,有則處理,無則等待。
ThreadLocal
ThreadLocal 可以在不同線程中互不干擾地存儲並提供數據,透過它可以很方便地獲取每個線程的 Looper。
為什麼要異步訪問 UI?
Android 規定 UI 操作只能在主線程中執行,子線程執行 UI 操作則會拋出異常。在 ViewRootImpl 中有如下方法:
void checkThread() { if (mThread != Thread.currentThread()) { throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }
顯然,對於 UI 這類耗時操作,我們不可能全部放在主線程中執行,因此就要採用異步方式。
系統為何不允許在子線程訪問 UI?
原因很簡單,Android 的 UI 線程是線程不安全的。
為什麼不採用加鎖方式處理 UI 線程?
- 會增加 UI 訪問的邏輯複雜度;
- 降低 UI 訪問效率。
至此,我們對異步消息處理的機制和必要性有了一個簡單的了解。
假設有如下需求:在子線程中更新 TextView 的文本顯示。
實現方式一:
mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { tv.setText(msg.obj.toString()); } } }; tv = (TextView) findViewById(R.id.tv); new Thread(new Runnable() { @Override public void run() { Message msg = new Message(); msg.what = 1; msg.obj = "神荼"; mHandler.sendMessage(msg); } }).start();
實現方式二:
mHandler = new Handler(); mHandler.post(new Runnable() { @Override public void run() { tv.setText("神荼"); } });
實現方式三:
runOnUiThread(new Runnable() { @Override public void run() { tv.setText("神荼"); } });
實現方式四:
tv.post(new Runnable() { @Override public void run() { tv.setText("神荼"); } });
實現方式五:
開啟加速——Google 的異步處理方案 AsyncTask(詳情請關注我的下一篇《Android 多線程編程之 AsyncTask 篇》)。
上述代碼都實現了同樣的處理效果,但實現上略有不同,想了解詳細原理,請跟進下面的源碼分析。
首先來看一下 Handler 的工作流程(來自郭神):

在第一種方式中,我們透過 handler.sendMessage() 方法發送一個 Message 對象,這個 msg 對象的第一站就是 MessageQueue。MessageQueue 主要包含兩個操作:插入(enqueueMessage)和讀取(next)。
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 { 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; }
上面的代碼明顯暴露了這傢伙維護的就是一個鏈表結構。當該方法被調用時,會向消息鏈表中插入新的消息對象。
再來看看 next:
Message next() { 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; } if (mQuitting) { dispose(); return null; } 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); } 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); } } } pendingIdleHandlerCount = 0; nextPollTimeoutMillis = 0; } }
嗯,210-237 行淋漓盡致地展現了 msg 是如何被取出並從鏈表中溢出的,沒什麼好說的。
我以前一直困惑 Looper 到底是個啥?是個類?還是個 final 類?不過這好像沒什麼意義。其實我們完全沒必要糾結它是什麼,只要知道它對 Handler 形式的異步處理具有決定性作用即可。實際上,我們在創建 Handler 時必須伴隨著兩個方法的調用。
Looper.prepare()
這裡假設你已經了解 ThreadLocal 是幹什麼的了,基於此來看該方法的源碼。
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)); }
可以看到,如果當前線程已存在與之「綁定」的 Looper,那麼透過本地 sThreadLocal 獲取即可,否則新建一個。重點來了:
Looper 對象所「綁定」的線程,也就是我們消息接收的線程。
所以,你現在知道了:Looper.prepare() 獲取與所在線程對應的 Looper 對象,決定消息接收處。
Looper.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; 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; } 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); } 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(); } }
這個玩法就更嗨了:先獲取 MessageQueue 對象,而後開啟自我輪迴模式(無限循環)。怎麼輪迴呢?看第 326 行,從 MessageQueue 中不斷取出 msg 對象,然後把該 msg 對象分發傳遞出去(338 行),msg.target 即為我們的 handler 對象。請注意,前方高能,Handler 源碼解析開始……
接上面的 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); } }
看到沒,該方法首先會判斷 callback 接口,若非空就直接處理,這也恰好對應了我們的第二種異步實現方式(簡單來說就是直接傳遞一個 Runnable,該 Runnable 最後會在 Looper 線程運行)。那麼第三種方式呢?也很類似,看代碼。
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
看到沒,就是第二種方式的封裝版,而且省去了 Handler 的創建。
你可能要問了,mCallback 是哪裡冒出來的,幹什麼用的?
對應這個問題,我只能說,看代碼。
public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
很明顯,這傢伙來自 Handler 的構造方法(不止一個),408 行已然說明一切。最後我們看到,在 dispatchMessage 中終究要執行終極方法 handleMessage(msg),於是消息對象來到了我們早已寫好的 handleMessage() 方法中,並在你 Looper「綁定」的線程執行(一般都是主線程啦)……
ThreadLocal 是一個線程內部的數據存儲類,透過它可以我們在指定線程中存儲數據,當然也只能獲取當前線程存儲的數據。
在 Handler 異步消息處理中,我們每個線程都要指定自己的 Looper 對象,如果沒有 ThreadLocal,我們可能需要用較為麻煩的方式去管理這些 Looper 對象,如用哈希表存儲等。
一個簡單的使用示例
private ThreadLocalmIntegerThreadLocal = new ThreadLocal<>(); mIntegerThreadLocal.set(111); new Thread("Thread_1") { @Override public void run() { mIntegerThreadLocal.set(222); Log.d("TAG2", mIntegerThreadLocal.get().toString()); Log.d("TAG", Thread.currentThread().getName()); } }.start(); new Thread("Thread_2") { @Override public void run() { mIntegerThreadLocal.set(333); Log.d("TAG3", mIntegerThreadLocal.get().toString()); Log.d("TAG", Thread.currentThread().getName()); } }.start(); Log.d("TAG1", mIntegerThreadLocal.get().toString()); Log.d("TAG", Thread.currentThread().getName());
輸出:

顯然,結果表明同一個對象在不同線程有著不同的值。再來看一下它內部的源碼實現(以搞懂源碼為目標)。首先是 set 方法。
public void set(T value) { Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values == null) { values = initializeValues(currentThread); } values.put(this, value); }
可以看到,ThreadLocal 能根據不同線程維護不同的 Values 對象(在 Thread 內部產生),進而存儲、獲取不同的數據,更具體的可以自行查閱源碼。
再來看下 get。
public T get() { // Optimized for the fast path. Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values != null) { Object[] table = values.table; int index = hash & values.mask; if (this.reference == table[index]) { return (T) table[index + 1]; } } else { values = initializeValues(currentThread); } return (T) values.getAfterMiss(this); }
和 set 類似,清楚明白,就不多說了。
聊了這麼久,有人可能會問:你說使用 handler 必須要調用 Looper 的 prepare 和 loop 方法,那麼主線程(ActivityThread)並沒看到調用啊,你淨扯犢子呢?
有此疑問的道友先息息火,關於這個問題其實很簡單,Android 已經為我們做好了封裝,而且第一個方法調用的是 Looper.prepareMainLooper()。
public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
OK,到此為止,我相信你應該徹底搞懂了 Handler 的異步消息機制。如果還有什麼疑問,歡迎下方留言;當然,我還是建議你能抽點時間自己去一點點地閱讀分析 Handler 的源碼,這樣才能真正深刻地理解並牢記。
Android 基礎入門教程——13 種 Drawable 全解析(下篇)
本節引言 在這個單元裡,我們要把剩下四種 Drawable 一次學完,它們分別是 LayerDrawable、TransitionDrawable、LevelListD
自訂 TextView 連結的單擊行為:用 ClickableSpan 觸發任意 Activity
先前介紹過 <a> 標籤,以及 TextView 自動辨識的特殊文字(網址、電話號碼、Email 等),這些都能透過單擊觸發對應動作。這些預設行為已能滿足大多
C++ 透過 JNI 呼叫 Android 彈出提示框:兩個關鍵錯誤與解法
用 NDK 寫 C++ 時想反過來呼叫 Java 層彈一個 AlertDialog,聽起來簡單,實際上踩了兩個坑:一個是 JNI 區域參照失效,一個是 Context 用
Android 自動掛斷電話的實作:透過 AIDL 呼叫 ITelephony
透過前面《AIDL 小結》與《AIDL 深入》兩篇文章,相信各位對 Android 的 AIDL 機制已經有了基本認識。這次我們就來動手實作一個實用的功能——自動掛斷電話