Handler之IdleHandler

IdleHandler是什么?

/**
 * Callback interface for discovering when a thread is going to block
 * waiting for more messages.
 */
public static interface IdleHandler {
    /**
     * Called when the message queue has run out of messages and will now
     * wait for more.  Return true to keep your idle handler active, false
     * to have it removed.  This may be called if there are still messages
     * pending in the queue, but they are all scheduled to be dispatched
     * after the current time.
     */
    boolean queueIdle();
}

IdleHandler是定义在MessageQueue里面的一个Interface,它在当线程开始阻塞等待消息的时候会调用的一个接口;当消息队列中的消息已用完或着等待更多消息时调用。返回true以保持IdleHandler处于活动状态,返回false以将其删除。如果队列中仍有挂起的消息,则可以调用此命令,但这些消息都计划在当前时间之后发送。

IdleHandler使用方法

//我们在子线程开启一个Looper
Handler mHandler;
new Thread(){
    @Override
    public void run(){
        //初始化Looper
        Looper.prepare();
        //创建Handler
        mHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Log.i("TAG","接收线程:"+Thread.currentThread().getId()+"收到Message");
            }
        };
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                //当前线程如果Looper获取消息处于阻塞状态会调用该方法
                Log.i("TAG","运行IdleHandler");
                //返回true说明重复使用IdleHandler
                //返回false则使用后删除该IdleHandler
                return true;
            }
        });
        //开始循环读取消息
        Looper.loop();
    }
}.start()

//然后我们开始发送1秒间隔Message
for (int i = 0 ; i < 5 ; i++){
    //每个消息间隔1000ms
    mHandler.sendMessageDelayed(Message.obtain(),1000*i);
}
//打印日志如下,间隔1000ms之间会执行IdleHandler的逻辑
I/TAG: 接收线程:4660收到Message
I/TAG: 运行IdleHandler
I/TAG: 接收线程:4660收到Message
I/TAG: 运行IdleHandler
I/TAG: 接收线程:4660收到Message
I/TAG: 运行IdleHandler
I/TAG: 接收线程:4660收到Message
I/TAG: 运行IdleHandler
I/TAG: 接收线程:4660收到Message
I/TAG: 运行IdleHandler

根据上面例子看出,发送的Message直接的间隔为1000ms,意味着在MessageQueue#next()获取每个Message之间,会阻塞1000ms,而在这1000ms就会调用IdleHandler,现在我们分析下源码,IdleHandler是怎么被调用的

//MessageQueue.java
//存放IdleHandler
private final ArrayList mIdleHandlers = new ArrayList();
//添加IdleHandler
public void addIdleHandler(@NonNull IdleHandler handler) {
    if (handler == null) {
        throw new NullPointerException("Can't add a null IdleHandler");
    }
    synchronized (this) {
        mIdleHandlers.add(handler);
    }
}
//移除IdleHandler
public void removeIdleHandler(@NonNull IdleHandler handler) {
    synchronized (this) {
        mIdleHandlers.remove(handler);
    }
}
//调用IdleHandler
Message next() {
    //...省略部分代码
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    //开始循环找出下个执行Message
    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;
            //下面代码作用是如果存在同步屏障则找出异步Message
            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());
                //一般为同步消息,isAsynchronous = false
            }
            if (msg != null) {
                //Message对象不为空
                if (now < msg.when) {
                    //当前时间小于Message的执行时间
                    // 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 {
                    //否则返回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 {
                //没有可执行的Message对象
                // No more messages.
                nextPollTimeoutMillis = -1;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            //只有当没有可执行Message或者Message对象执行时间需要等待时,才会走下面代码
            // 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.
            //第一次循环,记录IdleHadnler的数量
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                //如果不存在IdleHandler,则跳出本次循环
                // 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.
        //开始循环执行IdleHandler
        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) {
                //如IdleHandler返回false,则移除IderHandler
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        // 重制pendingIdleHandlerCount = 0,这个变量在循环读取Message队列之前是被初始化为-1,所以在第二次循环和之后,在上面逻辑会直接跳出本次循环
        //if (pendingIdleHandlerCount <= 0) {
        //    //如果不存在IdleHandler,则跳出本次循环
        //    // No idle handlers to run.  Loop and wait some more.
        //    mBlocked = true;
        //    continue;
        //}
        // 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;
    }
}

总结

IdleHandler会在Looper.loop()的MessageQueue.next()获取消息的时候,如果消息队列为空,或者消息队列中下个可执行的Message需要等待,则会循环遍历且执行MessageQueue中的mIdleHandler集合,而且只会在next()方法中,遍历消息队列的第一次得到执行;

你可能感兴趣的:(Handler之IdleHandler)