前言
上篇文章敘述了 Handler 的用法和避免因爲不當使用 Handler 引起內存泄露的方法。這篇文章將從源碼分析 Handler 消息機制的實現。
Looper
我們知道要想使用 Handler 就必須在當前線程裏初始化 Looper,我們初始化 Looper 的做法是調用 Looper.prepare() 方法。然後調用 Looper.loop() 方法。首先,我先來看 Looper.prepare() 的源碼:
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));
}
由上面源碼可以看出,在 Looper 的 prepare() 方法裏調用了 sThreadLocal.set(new Looper(quitAllowed))。sThreadLocal 的類型是 ThreadLocal 。 ThreadLocal 是一個線程內部的數據存儲類,通過它可以在指定的線程中存儲數據,數據存儲以後,只能在指定的線程中可以獲取到存儲的數據,對於其他線程來說則無法獲取到數據。這裏通過 ThreadLocal 的 set 方法將一個 Looper 對象存儲到當前線程中。
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.loop() 方法的主體是一個死循環。只有當 MessageQueue 的 next() 方法返回 null 的時候纔會跳出循環。但是 MessageQueue 的 next() 方法是一阻塞的方法,當 MessageQueue 中沒有消息的時候 next() 方法會阻塞。當調用了 MessageQueue 的 quit 或者 quitSafely 方法時 MessageQueue 的 next 方法就會返回 null。
如果 MessageQueue 的 next 方法返回了新消息,將執行 msg.target.dispatchMessage(msg),這裏的 msg.target是發送這條消息的 Handler 對象,這樣 Handler 發送的消息最終交給他的 dispatchMessage 方法處理。而 Handler 的 dispatchMessage 方法是在創建 Handler 時所使用的 Looper 中執行的,所以將代碼切換到了 Looper 所在的線程中執行了。
Handler 和 MessageQueue
先來看 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 方法取出當前線程的 Looper,如果當前線程還沒有初始化 Looper,將拋出異常。
Handler 的主要工作就是發送和處理消息。Handler 發送消息是通過 post 和 send 的一系列的方法來實現的。但他們最終都要調用 Handler 的 sendMessageAtTime 方法。
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
由上述代碼可以看出,Handler 的 sendMessageAtTime 方法會調用 enqueueMessage,而 enqueueMessage 調用了 MessageQueue 的 enqueueMessage 方法。
下面看 MessageQueue 的 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("MessageQueue", 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;
}
由上述代碼可以看出,Handler 發送消息是向消息隊列中插入一條消息, MessageQueue 的 next 方法會返回這條消息給 Looper 交給 Handler 處理。這時 Handler 的 dispatchMessage 方法會被調用,Handler 進入處理消息的階段。
Handler 的 dispatchMessage 方法的實現如下所示:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在 Handler 處理消息的過程如下:
首先判斷 Message 的 callBack 是否爲空,不爲空則調用 handleCallback 方法。callBack 實際是 Runnable 對象,而 handleCallback 方法則調用了 Runnable 的 run 方法。如果 Message 的 callBack 爲空則判斷 mCallBack 是否爲空。不爲空這調用它的 handleMessage 方法。mCallBack 是個接口,通過 CallBack 可以使用 Handler(Callback callback) 來創建 Handler 的對象,
而不用派生 Handler 的子類。最後調用 Handler 的 handlerMessage 方法處理消息。