一個Activity多個Handler時,Message是如何傳遞的
最近在面試,被面試官問到如果一個Activity有多個handler時候,怎樣知道handler1傳送的訊息不會被handler2接收,同理handler2傳送的訊息不會被handler1接收。
回來以後看原始碼才發現原來是這樣的:
平時我們直接new Handler(),原始碼裡面執行的是
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
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;
}
我們看到在第二段程式碼中,mLooper = Looper.myLooper();獲取了主執行緒中的那個looper物件,判斷mLooper==null的時候,丟擲了一個異常,說明了不能線上程裡面建立handler,如果必須要用的話,需要呼叫Looper.prepare()方法。mLooper不為null的情況下,mQueue = mLooper.mQueue,獲取的是MessageQueue佇列,mCallback = null,mAsynchronous = fasle;
我們順便看一下Looper.prepare()的原始碼
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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()的時候,相當於new Looper(quitAllowed)了一個新Looper設定到新執行緒中。這樣一個thread就有了一個Looper.
繼續看當我們呼叫sendMessage的時候,我們看一下原始碼裡面是怎麼執行的:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
“
一步一步的往下走我們看到在enqueueMessage()方法裡面有一個,
msg.target = this;這句話就是重點,就是說我們通過sendMesasge(msg)一層一層的傳遞訊息,最後這個msg.target=this就是把當前的這個handler標記給這個當前我們傳送的msg,然後再把這個打好標記的資訊新增到訊息佇列中。
我們再看看Looper裡面的原始碼
/**
* 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
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();
}
}
我們看到 msg.target.dispatchMessage(msg);這一句是,直接將這個訊息交給了傳送這個訊息的handler處理。
繼續看handler中的dispatchMessage原始碼:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看到Looper把訊息分發給handler, handler最終拿到訊息呼叫handleMessage(msg),此時我們在前臺呼叫的時候重寫的handleMessage(msg)拿到的這個msg就是我們需要處理的Message.這樣就完成了handler1把訊息傳遞,然後把這個訊息打上這個handler1的標記,最後looper再拿到打上這個handler1標記的訊息,再分發給handler1,此時handler1拿到的就是它上次傳送的那個訊息.
因為這樣就保證了一個Activity中可以有多個handler,同時handler傳送訊息,各自接收各自的訊息,這樣有序的進行,這樣也不會出錯。
看來得經常看看原始碼才能解釋、理解的清楚這些機制。