什么是Handler机制
在Android开发的过程中,会将耗时的一些操作放在子线程(work thread)中去执行,然后将执行的结果告诉UI线程(main thread),因为UI的更新要通过Main thread来进行(其实特殊子线程也可以更新UI)。那么这里就涉及到了如何将子线程的数据传递给主线程的问题。
所以Android系统提供了一个消息传递的机制——Handler,可用于将子线程的数据传递给主线程,其实,Handler不仅仅能将子线程的数据传递给主线程,它能实现任意两个线程的数据传递。
Handler机制运行流程
一、Handler机制四大核心类
- Handler
Handler类就像工人一般,往传送带上发送Message。 - Message
Message就好比传送带上的货箱,货箱里装着要传送的物品。 - MessageQueue
MessageQueue如同一个传送带,里面存放着一个个的Message。在Handler机制中,MessageQueue是一个优先级队列,是按传入的执行时间来进行入队出队操作。 - Looper
Looper就像传送带的轮子,一直循环执行。
二、Handler源码分析
通过阅读Handler类源码可以看到如图以下发送消息的方法最终都是调用了MessageQueue的enqueueMessage方法。
三、MessageQueue源码分析
1、MessageQueue队列
1)MessageQueue
是一个优先级队列,优先级是以要延迟执行的时间为判断依据,时间越短,执行优先级越长,如果延迟执行时间都为0,则插入到此节点的前面。
2)如果执行时间不为0,传过来的时间是按入参+系统时间为值,系统时间是越来越大,所以不可能出现时间相等的情况(时间为0除外)。
这里可以查看Handler中的sendMessageDelayed
源码,如下所示:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
// 延迟时间是调用了系统时间+延迟时间
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
3)MessageQueue是在Looper类的 构造方法中 创建的,所以 一个Looper 对应一个 MessageQueue;
2、enqueueMessage方法
enqueueMessage方法主要作用是往消息队列中存消息,即入队方法。
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;
// 注释1:当不存在消息或者当前要执行的时间为0,也就是立即执行或者当前延迟执行时间小于队列中的消息延迟时间的时候
// 将当前Message插入到队列最前面的位置(延迟执行时间为0的都插入到队列的最前面),如果线程阻塞则唤醒
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
// 根据时间的顺序调用 msg.next,给每一个消息指定它的下一个消息是什么
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();
// 注释2:如果不满足上述条件,则需要遍历整个消息队列,依次判断每个Message要延迟执行的时间,对比之后插入到其中,如果比某个几点要延迟执行的时间小,则插入到这个节点的前面进行执行
Message prev;
for (;;) {
prev = p;
p = p.next;
// 如果判断时间比某个节点小则跳出for循环,之后执行插入到此节点的前面的逻辑
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;
}
这段代码有几个点要分析一下:
- 注释1:当不存在消息或者当前要执行的时间为0,也就是立即执行或者当前延迟执行时间小于队列中的消息延迟时间的时候
将当前Message插入到队列最前面的位置(延迟执行时间为0的都插入到队列的最前面),如果线程阻塞则唤醒。 - 注释2:如果不满足上述条件,则需要遍历整个消息队列,依次判断每个Message要延迟执行的时间,对比之后插入到其中,如果比某个几点要延迟执行的时间小,则插入到这个节点的前面进行执行。
3、next方法
next方法负责从消息队列中取出Message,方法返回Message 对象。
- 注释1:执行循环,不断从队列中获取Message,因为可能有Message插入到队头部,所以不断循环获取;
- 注释2:获取当前系统时间;
- 注释3:获取队列头消息;
- 注释4:队头消息时间大于当前时间,即队头消息还没到执行时间;
- 注释5: 当开始执行时,就从队列中取出Message进行返回。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
// 注释1:执行循环,不断从队列中获取Message,因为可能有Message插入到队头部,所以不断循环获取
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// 调用native层的nativePollOnce方法,
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
// 注释2:获取当前系统时间
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
// 注释3:获取队列头消