Android Handler機制
Handler是什麼
Handler是Android設計者Google設計用於的一套更新UI的機制,也是一套訊息處理的機制,我們可以傳送訊息,也可以通過它來處理訊息,Handler在我們的 framework中是非常常見的。
Android 在設計的時候,就封裝了一套訊息建立、傳遞、處理機制,如果不遵循這樣的機制就不能更新UI資訊,並丟擲異常資訊。
為什麼要設計只能通過Handler機制來更新UI呢
其實最根本的目的就是解決多執行緒併發問題。例如,當我們在一個Activity中執行來多個執行緒並更新一個UI控制元件,如果沒有這個Handler機制,將可能出現異常情況,我們可以通過加鎖的來解決多執行緒併發問題,但加鎖帶來的問題就是效能下降。
針對以上的問題,Google設計android時就已經為我們考慮好了,通過遵循Handler機制來解決這個問題。
如何使用
關於如何使用Handler本文就不再敘述了,因為使用起來十分簡單,隨便Google一下也都有介紹。
原理
那麼Handler的原理是什麼呢?或者說Google開發者們是如何實現的Handler機制呢?要想弄清楚原理,我們還是從原始碼中來了解一下吧。
一、 在解讀原始碼之前,我們先認識以下幾個Handler機制關鍵的Class物件。
-
Looper:
1.內部包含一個訊息佇列 MessageQueue,所有的 Handler 傳送的訊息都走向(加入)這個訊息佇列。
2.Looper.Looper方法,就是一個死迴圈,不斷地從 MessageQueue 取得訊息,如果有訊息就處理訊息,沒有訊息就阻塞。
-
MessageQueue
MessageQueue 就是一個訊息佇列,可以新增訊息,並處理訊息。
-
Handler
Handler封裝了訊息的傳送(主要是將訊息傳送給誰(預設是Handler自己),以及什麼時候傳送)。Handler內部會跟 Looper 進行關聯,也就是說,在 Handler 的內部可以找到 Looper,找到了 Looper 也就找到了 Message。在 Handler 中傳送訊息,其實就是向 MessageQueue 佇列中傳送訊息。
二、 接下來,我將從如何使用開始給大家深入解析原始碼。
通常我們使用Handler更新UI時,都是直接去new一個Handler的例項。然後覆寫Handler.handleMessage方法,然後在子執行緒中傳送訊息通知主執行緒更新UI。
Handler handler = new Handler() { @Override public void handleMessage(Message msg) { //更新UI } }; ... new Thread(new Runnable() { @Override public void run() { //子執行緒傳送message,通知主執行緒更新UI handler.sendEmptyMessage(1); } }).start();
首先我們來看一下Handler的構造方法。
public Handler() { this(null, false); } public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> 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構造方法中通過Looper.myLooper()獲取到當前執行緒(UI執行緒)的Looper物件,那麼當前執行緒如何建立這個Looper物件呢?
其實在Android主執行緒ActivityThread的入口main方法中,通過呼叫Looper. prepareMainLooper()方法初始化了Looper物件,並在方法最後呼叫了Looper.loop()方法開啟了這個訊息輪訓。原始碼如下:
public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy.We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); // Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter()); // Make sure TrustedCertificateStore looks in the right place for CA certificates final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
於是我們在任意Activity中或者說主執行緒任意位置new Hander()的時候,通過mLooper = Looper.myLooper();獲取當前執行緒的Looper物件。有同學就好奇了這個Looper.myLooper()方法如何獲取到當前的Looper物件的。
接下來,我們就一起看看這個Looper原始碼。
public static void prepare() { prepare(true); } 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)); } public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
在myLooper()方法中我們注意到sThreadLocal變數,他其實是ThreadLocal<Looper>物件,用於存放這個Looper物件的。在prepare()方法中建立一個Looper物件並存放到這個sThreadLocal.set(new Looper(quitAllowed))。
又注意到Looper的構造方法。
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
在這個建構函式中建立了MessageQueue物件。
看到這裡,大家應該可以將Handler、Looper、MessageQueue三者到關係弄清楚了。接下來再看一下Looper中關鍵的方法loop()。
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the 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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } 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(); } }
這裡通過一個死迴圈,不斷的從訊息佇列中讀取訊息,並通過msg.target.dispatchMessage(msg);將message傳送給handler自己。
總結
Handler 負責傳送訊息,Looper 負責接收 Handler 傳送的訊息,並直接把訊息回傳給 Handler 自己,MessageQueue就是一個儲存訊息的容器。
【附錄】

資料圖
需要資料的朋友可以加入Android架構交流QQ群聊:513088520
點選連結加入群聊【Android移動架構總群】: 加入群聊
獲取免費學習視訊,學習大綱另外還有像高階UI、效能優化、架構師課程、NDK、混合式開發(ReactNative+Weex)等Android高階開發資料免費分享。