int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// 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.
//首次遍历,原始值是-1,故进入
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 MessageQueue.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 MessageQueue.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;
设置pendingIdleHandlerCount
的默认值为-1,这个会在判断是否还有需要通知的IdleHandler的时候有用。如果是初始状态,会获取一次待通知的IdleHandler
列表。如果存在需要通知的IdleHandler
,会逐一编译进行通知,并且根据keep = idler.queueIdle();
的返回值,来决定是否需要移除监听。
背景我们的在业务开发的过程中,可能会遇到这样子的情况,需要再UI线程空闲的时候,做一些操作,那应该怎样子实现呢?MessageQueue.IdleHandlerMessageQueue给我们提供了一个IdleHandler的接口,其定义如下: /** * Callback interface for discovering when a thread is going to...
转载出自:http://bbs.51cto.com/thread-1094228-1.html
MessageQueue.IdleHandler可以用来在线程空闲的时候,指定一个操作;有点类似Handler.postDelayed(Runnable r, long delayMillis),都是在将来的某一个时间
执行一个操作。
不过,使用IdleHandler的好处在于可以不用指定一个将来
IdleHandler是什么?
IdleHandler是包含在MessageQueue类中的一个接口,内部只包含一个方法,在消息队列空闲(没有消息或者第一个需要处理的消息在将来执行)时被回调
publicstaticinterfaceIdleHandler{//当消息队列空闲时会被回调,返回值表示是否会被重复执行//返回true,会在mIdleHandlers...
作者:谷言,腾讯移动客户端开发工程师商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处。原文链接:http://wetest.qq.com/lab/view/352.html
WeTest 导读
干货!干货!或许可以是一种处理问题的新思路哟!
我们知道android是基于Looper消息循环的系统,我们通过Handle...
# 使用 PeekCompleted 方法查看队首消息但不弹出
queue.Enqueue("第四条消息")
next_message = queue.peekCompleted()
print("下一条消息是:", next_message)
# 输出结果:
# 下一条消息是: 第四条消息
希望这个例子可以帮助你理解 MessageQueue 类以及 PeekCompleted 事件的基本用法。如果你有任何问题或需求,请随时向我提出。