https://wiki.sankuai.com/pages/viewpage.action?pageId=390507729
加深自己对Handler——Message机制的理解。
首先我们在子线程创建一个Handler,但之前我们必须调用Looper.prepare(),原因我们在源码中可以看到
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;
}
我们可以看到调用Looper.myLooper()获取到了mLooper对象,可以想到获取到的Looper对象是我们当前线程对应的Looper对象。来看一下myLooper方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
sThreadLocal.get()是通过当前线程获取Looper对象,如果获取不到就会返回空,mLooper为空就会抛出"Can't create handler inside thread that has not called Looper.prepare()"的异常,至于Looper.prepare()正是为当前的线程设置了一个新的Looper对象。
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对象进去。Looper的构造
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在构造Looper的时候创建了新的mQueue,mThread标记为当前的Thread。我们在向上看,创建Handler的部分将mQueue = mLooper.mQueue;将消息队列指定为Looper的消息队列。接下来就是发送消息的过程了,发送消息的方法最终调用的都是
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
所以说即使我们将延时指定为负数,传进去的也是0,我们主要看的还是sendMessageAtTime
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);
}
这里只做了一个判空处理,判断当前的Handler对应的MessageQueue是否为空,让后交给enqueueMessage处理,我们看方法名就知道这是入队的方法,而消息一定是插入到Handler对应的MessageQueue里。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
确实是这样,调用的是传入的MessageQueue的入队,msg的target指的就是当前的Handler。
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
msg的markInUse标记当前消息已经入队,如果当前的mMessages为空,或者当前的时间为0,或者先加入的msg时间比mMessage的时间小,就将mMessage指定为新传入的消息,下面实现的是按照when大小的链表插入排序,这里我们看到,消息队列并不是一个队列,而是按照when排序的一个链表,而mMessage表示头,即将处理的消息。这样消息入队的过程就看完了,接下来是出队的过程,我们需要到Looper.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;
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);
}
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();
}
}
这里拿到的me仍然是当前线程的的队列,queue.next()就是拿到当前队列的mMessage,也就是消息队列的头部,然后再将下一条Message指定为mMessage。我们还记得msg.target指的是msg对应的Handler,dispatchMessage会交给指定的Handler来处理消息。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这个就不解释了吧,handleMessage(msg)对消息进行了处理,延时的实现是在queue.next()里,使用循环停等的方式,loop的for循环会不停地取消息,直到消息为空循环结束。这样Handler的流程也就分析的差不多了。