经历了一段时间的学习和总结,在这篇博客中写下自己对Handler的理解。话不多说,直接上图。
首先,我们需要知道的是,如果一个线程想要使用Looper,需要调用Looper.prepare()。刚开始学的时候,我便异或,为什么主线程里面没有调用这个方法呢。原来在我们启动一个Activity时,通过ActivityThread内部已经帮我们得到了这个Looper。代码如下:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
那么在子线程中调用Looper.prepare()时,又是怎么做的呢?接下来,我们一步一步分析Looper这个类。首先,在Looper中会有一个变量:mMessageQueue。在初始化Looper时,便会实例化MessageQueue。在Looper中还有一个ThreadLocal<Looper>(用来和当前线程绑定,该ThreadLocal只被当前线程拥有,其他线程无法访问)。调用Looper.prepare()方法时,会将一个Looper存入该ThreadLocal,且只能存入一个。
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));
}
有发才有收,接下来我们继续分析Handler源码,了解Handler是怎么发送消息的。在Handler中我们会实例化两个变量:mLooper,mMessageQueue。这两个变量指向Looper和Looper中的消息队列。发送消息的方法有很多种,但最终都会指向enqueueMessage(...),所以我们分析enqueueMessage(...)即可。在这个方法中,会将Handler一并发送出去,以便后期从MessageQueue中分发事件。
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;
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最后,会根据消息队列中有无消息,将该消息放入消息队列。如果没有消息,就放在首位,有消息的话,就将消息放置队尾。
接下来我们分析消息到达MessageQueue时的处理,以及Looper是怎么将消息从队列中提取出来的,需要注意的是消息队列的实现是一个单链表,方便消息的插入和提取。
在Looper中会调用loop()的方法,通过Looper.myLooper()拿到Looper并获得消息队列,在一个死循环中从消息队列提取出消息并调msg.taret.dispatchMessage(msg);此方法会进入Handler,并根据是否有回调接口的实现以及msg.callback != null的条件来进行消息的接受。接着调用msg.recycle()从消息队列中清空该消息。
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
从上面的源码中可以知道,我们会调用next()方法来获得下一个Message。那么next()是怎么实现的呢?我们继续往下看。
在next()方法中,我们会将消息队列的第一个数通过markInUse()标记为可用并返回,并通过mMessage = msg.next将链表指针向后传递,最后将msg设置会null。这样,便可以轮询出消息队列中的所有消息。
至此,Handler机制粗略分析完毕,感谢阅读。