Handler消息延迟原理
开发过程中经常会使用Handler设置一些延时任务,Handler是如何实现消息延迟的呢?在Handler、Looper、MessageQueue消息机制原理一文应该也有所了解其原理,这里单独剖析一遍。
1、post系列方法
提到消息延迟,第一时间想到的就是Handler的postDelayed()方法。查看API 30的Handler源码,一共有如下七个post任务的方法:
①post(Runnable r):最常用的方法,通常在子线程将任务切回到主线程执行
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
②postAtTime(Runnable r, long uptimeMillis)
public final boolean postAtTime(@NonNull Runnable r, long uptimeMillis) {
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
③postAtTime(Runnable r, Object token, long uptimeMillis)
public final boolean postAtTime(Runnable r, @Nullable Object token, long uptimeMillis) {
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
④postDelayed(Runnable r, long delayMillis)
public final boolean postDelayed(@NonNull Runnable r, long delayMillis) {
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
⑤postDelayed(Runnable r, int what, long delayMillis)
public final boolean postDelayed(Runnable r, int what, long delayMillis) {
return sendMessageDelayed(getPostMessage(r).setWhat(what), delayMillis);
}
⑥postDelayed(Runnable r, Object token, long delayMillis)
public final boolean postDelayed(Runnable r, @Nullable Object token, long delayMillis) {
return sendMessageDelayed(getPostMessage(r, token), delayMillis);
}
⑦postAtFrontOfQueue(Runnable r)
public final boolean postAtFrontOfQueue(@NonNull Runnable r) {
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
看到post系列的方法是做了一些封装,内部还是通过Handler的核心方法sendMessage发送消息。通过getPostMessage(Runnable r)方法将Runnable封装成Message消息。
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
2、send系列方法
send消息是很常见的,Handler提供7个相似的方法:
①sendMessage(Message msg):Android开发者用的最多的消息发送方法
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
②sendEmptyMessage(int what)
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
③sendEmptyMessageDelayed(int what, long delayMillis)
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
④sendEmptyMessageAtTime(int what, long uptimeMillis)
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
⑤sendMessageDelayed(Message msg, long delayMillis)
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
⑥sendMessageAtTime(Message msg, long uptimeMillis):最终都会调用这个方法
public boolean sendMessageAtTime(@NonNull 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);
}
⑦sendMessageAtFrontOfQueue(Message msg)
public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg) {
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, 0);
}
3、消息延迟源码分析
捋完Handler中的post和send消息方法,从源码调用流程分析一下其中的延迟原理。
3.1、sendMessageAtTime()
除了第二节中的第⑦个方法,无论通过其它哪那个方法最终都会调用sendMessageAtTime(Message msg, long uptimeMillis)方法发送消息,将Message进入队列。
public boolean sendMessageAtTime(@NonNull 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);
}
不管通过哪个方法调用,是否需要延迟,最终都会转换并传入一个uptimeMillis参数。它的含义是:消息应该被传递的绝对时间,使用SystemClock.uptimeMillis()时间为基准(自启动以来的毫秒数,不计算深度睡眠所花费的时间)。
3.2、enqueueMessage()
调用Handler中的enqueueMessage()方法,将Message放入Handler持有的MessageQueue消息队列mQueue中。
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);
}
Handler的任务到这里就结束,进入MessageQueue中。
3.3、MessageQueue#enqueueMessage()
接下来是关键,让我们看看消息队列MessageQueue的核心方法之一enqueueMessage(Message msg, long when):
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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;
}
①根据Message的时间when插入MessageQueue队列中合适的位置
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
②因为Message是以链表的形式组织起来的,每个Message中都有一个next“指针”指向下一条消息
public final class Message implements Parcelable {
public int what;
...
Handler target;
Runnable callback;
public long when;
// sometimes we store linked lists of these things
Message next;
...
}
这段代码经典的链表插入,将Message按照时间先后插入到Message链中合适的位置
Message p = mMessages;
{
Message prev;
...
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
这样的链表插入时间复杂度妥妥的O(n),消息过多会导致应用卡顿也有可能的。
3.4、消息取出 next()
消息如何取出呢,在Handler、Looper消息机制的源码中我们知道通过Looper的的loop()方法开启循环,通过MessageQueue的next()方法不断的从消息队列中取出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;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
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) {
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 {
// 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.
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;
}
}
这段方法非常长,只需要关注其中的核心一段:for循环遍历队列取出Message,关键点是nextPollTimeoutMillis时间变量,当没有Message可以取出就休眠,每次插入Message同样会唤醒并且重新计算时间。
举个例子:只发送了一个Message,但是这个Message延迟了10s,这时就没有Message可以取出,10s后才有Message可以取出,这10s内就阻塞不会有消息被取出。
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
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());
}
这里有两个Native操作flushPendingCommands()和nativePollOnce(long ptr, int timeoutMillis),底层涉及到Linux的epoll,是Linux的一种I/O多路复用机制(略)。