=============================================================================
Handler持有了一个消息队列MessageQueue
对象mQueue
。这个对象是Handler实例构造的时候,通过Looper传递过来的。当使用无参构造方法时,这个Looper为Looper.myLooper()
。
public Handler() {
// 。。。
mLooper = Looper.myLooper();
mQueue = mLooper.mQueue;
}
而Looper类又是通过 ThreadLocal 来实现线程和Looper对象一一对应的。Looper.myLooper()
即是当前线程所对应的Looper。
也就是说,Handler中的消息队列,其实是当前线程对应的Looper的消息队列。
那么,要理解Handler的原理,就要先理解Looper和消息队列的原理。
1.1 Looper
事情又要回到ActivityThread
中说起,这相当于是一个Android程序的主线程,main
方法就在其中。
ActivityThread.main()
public static void main(String[] args) {
// …
Looper.prepareMainLooper();
Looper.loop();
throw new RuntimeException(“Main thread loop unexpectedly exited”);
}
在这里,调用了Looper的两个方法,prepare
和loop
,启动了主线程的Looper。Looper的结构相对来说还是比较简单的,其中最主要的就是这两个方法了。
Looper.prepare()
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException(“Only one Looper may be created per thread”);
}
sThreadLo
cal.set(new Looper(quitAllowed));
}
在Looper内部,有一个ThreadLocal<Looper>
类型的静态变量sThreadLocal
。 而prepare的过程很简单,就是将当前这个Looper对象,保存到这个sThreadLocal
中。即:以sThreadLocal
为媒介,建立当前线程与当前Looper对象的对应关系。
Looper.loop()
这是Android程序中最重要的机制之一,也是Android程序能够一直运行的原因。以下是Looper.loop()
源码,删去了绝大部分,只保留了最关键的几行:
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;😉 {
Message msg = queue.next(); // might block
try {
msg.target.dispatchMessage(msg);
} // …
}
}
可以发现,loop()
函数其实是一个死循环;在这个循环中,不停地从消息队列中取下一条消息,然后分发给对应的Handler(msg.target
)进行处理。 “Looper”就是循环的意思,这正对应了loop()
方法中的这个死循环。在这个死循环里面,可以无限读取消息队列中的消息。使用quit()
方法可以退出这个循环;如果在主线程的Looper退出,也就意味着程序的结束——将会得到 java.lang.IllegalStateException: Main thread not allowed to quit.
的报错信息。
1.2 消息队列 - MessageQueue
- Message
Message消息是Handler传递信息的基本单位。在Handler中,不管是调用post(Runnable)
还是sendMessage(Message)
还是其他的什么,最终都会构建一个Message对象,并添加到消息队列mQueue
中。Message中保存了消息的类型、参数、对应的Handler等一些少量的数据。
在1.1中说到,Looper.loop()
会发起一个死循环,在消息队列中不停取值。那么,为什么这里不会卡死呢?
Looper#loop()
:
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;😉 {
Message msg = queue.next(); // might block
try {
msg.target.dispatchMessage(msg);
} // …
}
}
跳转到MessageQueue.next()
,看一下消息队列是怎么取下一条消息的。这里删去了大部分代码,只剩下核心的部分,方便梳理流程:
Message next() {
int nextPollTimeoutMillis = 0;
for (;😉 {
nativePollOnce(ptr, nextPollTimeoutMillis); // 会阻塞线程直到下一个消息到来
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message msg = mMessages;
if (msg != null) {
if (now < msg.when) { // 时候未到
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mMessages = msg.next;
msg.next = null;
msg.markInUse();
return msg;
}
}
}
}
}
nativePollOnce
是一个本地方法,它会阻塞线程直到下一个有消息来临。这类似于Java中的DelayQueue
,不同点是DelayQueue
是通过优先队列+锁实现的。 在MessageQueue中有一个Message类型的对象mMessage
,它保存着消息队列中最早的一条消息。当阻塞的线程被唤醒时,next()
方法会返回mMessage
,并且mMessage
重新赋值为mMessage.next
。 很容易发现,在消息队列中,所有未读的消息是通过链表的形式来保存的,每一个Message都是链表中的节点,Message#next
指向了链表中的下一个节点。
小结
-
Looper和拥有Looper的线程一一对应,通过ThreadLocal来实现。Looper和消息队列也是一一对应的。
-
Looper.loop()
中是一个死循环,会无限调用对应消息队列的next()
方法来获取下一个消息。 -
消息队列的
next()
方法会调用native方法nativePollOnce
阻塞线程,直到有新的消息来临将其返回。 -
消息队列实质上是以
Message
为节点的单向链表,其头节点为mMessage
。链表是按照Message的触发时间,即msg.when
,从早到晚排序的。
从发送消息开始。使用Handler的post(runnalbe)
、sendMessage(msg)
、sendMessageDelayed(msg, delay)
、Message的sendToTarget()
等等许多方法都可以发送消息。最终,这些方法都会进入Handler#enqueueMessage
方法。
- Handler#enqueueMessage(MessageQueue, Message, long)
enqueueMessage
方法的作用是将Message的target设置为本Handler,然后调用MessageQueue的enqueueMessage
方法。
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这个queue
即是Looper.mQueue
,即当前线程的消息队列。在这里,会使用msg.target = this
将Message与当前Handler绑定。 这里的uptimeMillis
是Message预定送达的时间,如果没有设置延迟,那么这个时间是SystemClock.uptimeMillis()
。
- MessageQueue#enqueueMessage(Message, long)
顾名思义,enqueueMessage
表示将新到来的消息入队。 删去了部分,只保留关键代码:
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
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;
}
这里做了两件事: 一、将这个Message按照传达时间的顺序插入到消息队列中; 二、如果消息队列当前是阻塞的,并且这个消息的传达时间成为了消息队列中最早的一个,那么就将线程唤醒。
当消息入队之后,消息发送的过程就已经完毕了,接下来就是等待取出消息了。
-
MessageQueue#next()
-
Looper#loop()
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;
}
这里做了两件事: 一、将这个Message按照传达时间的顺序插入到消息队列中; 二、如果消息队列当前是阻塞的,并且这个消息的传达时间成为了消息队列中最早的一个,那么就将线程唤醒。
当消息入队之后,消息发送的过程就已经完毕了,接下来就是等待取出消息了。
-
MessageQueue#next()
-
Looper#loop()