Handler Looper MessageQueue 之间的关系
handler在安卓开发中常用于更新界面ui,以及其他在主线程中的操作。内部结构大概图为:
1、handler持有一个Looper对象,这个Looper对象可以是自定义子线程的Looper,也可以是默认MainLooper。Looper主要作用就是不断循环MessageQueue中的Message,回调Handler的dispatchMessage方法。源码:
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);
}
//这里回调handler中的dispatchMessage方法
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();
}
2、Handler还持有MessageQueue对象的引用,用于sendMessage时,将消息添加到MessageQueue中。这样Looper就可以获取到最新的message。Handler中的MessageQueue其实就是Looper的MessageQueue成员属性。
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
所以一个大致的流程就是:
1、Looper在在不断的获取MessageQueue消息,调用handler的dispatchMessage方法
2、Handler.postMessage就是往Looper的MessageQueue中添加Message,并且设置message.target为Handler本身