【问题标题】:How the method postDelayed(Runnable runnable, Long delayMilliSeconds) works exactly? [duplicate]postDelayed(Runnable runnable, Long delayMilliSeconds) 方法是如何工作的? [复制]
【发布时间】:2015-10-28 22:04:34
【问题描述】:

我想知道 postDelayed(...) 方法何时执行,并且消息队列中有许多消息正在等待。在那种情况下,什么时候运行可运行对象?会在方法中定义的时间过去之后吗?或者它会等到它的角色进入消息队列?要不然是啥... ?

【问题讨论】:

    标签: android runnable android-handler postdelayed


    【解决方案1】:

    让我们查看源代码和文档:

    使 Runnable r 被添加到消息队列中,以便运行 经过指定的时间后。可运行的将运行 在此处理程序附加到的线程上。时基是 正常运行时间米利斯()。花在深度睡眠中的时间会增加额外的延迟 执行。

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

    现在让我们检查一下sendMessageDelayed

    在所有未决消息之后将消息排入消息队列 之前(当前时间 + 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?

    希望对您有所帮助。

    【讨论】:

    • 但是如果待处理消息的运行时间超过 delayMillis 怎么办?
    • 检查这个问题的接受答案:stackoverflow.com/questions/27240015/…
    • 这正是你想知道的。
    • 感谢 Rodrigo,这些链接非常有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2019-06-01
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多