如果一个Activity有多个handler时候,handler1发送的消息是否会被handler2接收,同理handler2发送的消息是否会被handler1接收?
答案是:不会,一句话谁发送的消息,谁处理,为什么,因为每个Message消息都会绑定一个target来指定这个消息由谁来处理。
1 Message消息在被发送时会被绑定Handler
追溯源码发现,无论使用Handler的哪个方法来发送消息,最终都会调用到下面方法来发送,在这里 msg对象会被绑定target,而这里的值为this,正是发送消息的Handler的本身,
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
2 Message消息在被处理的时候
追溯源码
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); 关键的这一句,msg调用了自身绑定的target的dispatchMessage方法来处理消息,而这里的target正是msg在被发送的时候所绑定的handler.