先分别介绍一下Handler,Looper,MessageQueue:
1、Handler,Handler封装了消息的发送
2、Looper,(1)内部包含一个消息队列(即messageQueue),所有的Handler发送的消息都要走向这个队列
(2)Looper.loop()是一个死循环,不断的从MessageQueue中取出消息,如果MessageQueue中有消息就处理消息,没有消息就阻塞。
3、MessageQueue,就是一个消息的队列(可以理解成一个数组)。
分析一下:
当我们new一个Handler的时候,看一下构造函数
<span style="font-size:14px;">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;
}</span>
我们看到已经拿到一个Looper对象
看下Looper 的构造函数<span style="font-size:14px;"> public static Looper myLooper() {
return sThreadLocal.get();
}</span>
调用了
sThreadLocal.get()返回一个Looper对象 ,sThreadLocal是一个ThreadLocal的对象,这也就是为什么每个activity都会有一个Looper的原因。
再看下Looper.loop()做了什么
<span style="font-size:14px;"> 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.recycle();
}
}</span>
可以看到 实际上就是不断的从MessageQueue中取出消息。
总结一下三者的关系:Handler负责发送消息,Looper负责接收Handler发送的消息,并把消息回传给Handler自己,MessageQueue是一个存储消息的容器。