一切从Android的Handler讲起(五):延迟消息实现原理与消息机制的基本原理
在一切从Android的Handler讲起(四):Looper消息获取中,肥柴的分析都是基于及时消息,那对于诸如postDelay的延迟消息,Handler中又是如何实现其延迟出发的呢?
一、延迟消息实现原理
我们重新来回顾一下MessageQueue内的获取消息的next()方法的源码。
/** MessageQueue.class */
@UnsupportedAppUsage
Message next() {
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
/** 注释1 Message获取 */
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
/** 注释2 计算Message执行时间与当前时间的差值,即延迟时间 */
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
/** 注释3 无需延迟,立即返回Message进行后续处理 */
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
/** 注释4 没有IdelHandler,重新进行循环 */
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
我们重点关注注释部分的相关代码,从中我们可以总结出如下关于延迟消息处理的大致流程。
1、首次进入next方法,nativePollOnce(long ptr, int timeoutMillis)从MessageQueue中获取表头Message;
2、获取Message的执行时间与当前时间进行判断,计算表头Message是否需要延迟,延迟时间为nextPollTimeoutMillis;
3、若当前时间小于Message执行时间,即now < msg.when,那么立即返回当前Message交由Handler处理;
4、需要延迟,则判断是否存在IdelHandler,不存在则进入下一个循环,执行nativePollOnce方法;
5、此时nativePollOnce(long ptr, int timeoutMillis)的入参nextPollTimeoutMillis即为需要延迟的时间,等待延迟时间后在触发获取Message;
从这里我们就知道:next()中如果当前链表头部的Message是延迟消息,则根据延迟时间进行消息队列阻塞,不返回给Looper Message,并设置定时唤醒,唤醒后,返回Message给Looper处理。
二、消息机制的基本原理
我们上面提到,如果是延迟消息,则通过nativePollOnce(long ptr, int timeoutMillis)设置了定时器延迟唤醒,那灵魂三连问来了。
1、nativePollOnce获取的是链表表头信息,那MessageQueue如何保证链表内获取的消息顺序从而保证执行顺序?
事实上,当调用enqueueMessage(Message msg, long when)方法,MessageQueue会根据Message的执行时间msg.when进行排序,链表头的延迟时间小,尾部延迟时间最大。
2、如果在延时唤醒的过程中,又来了一个立即执行的message又该如何呢?
依照上面的思路,立即执行的消息同样也会先入链表,然后唤醒线程获取表头message,看是否到了执行时间。由于立即执行的消息其实是一个延时为0的message,在一个延迟的链表中,必然会放入表头,而且是无延迟的,所以会立即取出返回给loop去执行了,loop处理完消息,继续来拿表头的message。
3、当整个链表都是延迟执行的message时,如果此时插入的message也是延时执行的,是否一定要唤醒呢?
如果插入的message并非插入表头,说明拿的下一个message也不是自己,完全可以让线程继续休眠,没有必要唤醒,因为此时的定时器到期唤醒后拿到的正是待返回和执行的表头message。
因此我们对于消息机制的基本原理有如下的总结:
1). 消息是通过enqueueMessage(msg)方法插入消息链表中的,并且按照message.when排序,链表头的延迟时间小,尾部延迟时间最大。
2). Looper.loop()通过MessageQueue中的next()去取消息。
3). next()中如果当前链表头部的message是延迟消息,则根据延迟时间进行消息队列会阻塞,不返回给Looper message,并设置定时唤醒,唤醒后,返回message给looper处理。
4). 如果在looper处于休眠中(要么链表为空,要么整个链表均为延时message),此时若有新的消息插入到链表头部则直接唤醒线程,looper继续判断步骤3)。
5). 最终Looper将表头message交给handler中的handleMessage处理,然后继续调用MessageQueue的next()方法,如果刚刚的延迟消息还是时间未到,则计算时间继续阻塞。
三、肥柴总结
肥柴总结一下延迟消息实现原理与消息机制基本原理的核心:只有当表头来了新消息,才会唤醒Loop来获取,Message要么立即执行,要么Loop刷新自我唤醒的定时器继续睡眠。
- - - - - 延迟消息实现原理与消息机制的基本原理篇完 - - - - -