postDelayed(Runnable runnable, Long delayMilliSeconds) 方法是如何工作的?

How the method postDelayed(Runnable runnable, Long delayMilliSeconds) works exactly?

我想知道方法postDelayed(...) 什么时候执行,消息队列中有很多消息在等待。在这种情况下,runnable 何时运行?会在方法中定义的时间过去之后吗?或者它会等到它的角色进入消息队列?或者是什么... ?

让我们检查一下源代码和文档:

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached. The time-base is uptimeMillis(). Time spent in deep sleep will add an additional delay to execution.

public final boolean postDelayed(Runnable r, long delayMillis) {
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}

现在让我们检查一下sendMessageDelayed:

Enqueue a message into the message queue after all pending messages before (current time + delayMillis).

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

因此,postDelayed 添加要在所有待处理消息之后但在正常运行时间 + 您设置的延迟之前执行的任务。

检查这个问题以获得更多解释: Does postDelayed cause the message to jump to the front of the queue?

希望对您有所帮助。