美文网首页
2020-03-08-Android的IdleHandler

2020-03-08-Android的IdleHandler

作者: 耿望 | 来源:发表于2020-03-08 09:57 被阅读0次

    之前介绍过Android的Handler机制

    https://www.jianshu.com/p/92b1f22dadeb
    2020-02-12-Android消息机制Handler

    今天简单看一下藏在MessageQueue里的另外一种消息处理机制IdleHandler。它的作用是在消息队列空闲的时候,执行一些不需要保证执行时机的任务。

    MessageQueue

    我们看到MessageQueue内部是定义了一个IdleHandler接口,并且维持了一个Array List数组,用来添加和管理Idle任务。

        private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
        private IdleHandler[] mPendingIdleHandlers;
        /**
         * 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();
        }
    

    同时MessageQueue提供了两个方法来进行Idle任务的添加删除:

        public void addIdleHandler(@NonNull IdleHandler handler) {
            if (handler == null) {
                throw new NullPointerException("Can't add a null IdleHandler");
            }
            synchronized (this) {
                mIdleHandlers.add(handler);
            }
        }
        public void removeIdleHandler(@NonNull IdleHandler handler) {
            synchronized (this) {
                mIdleHandlers.remove(handler);
            }
        }
    

    根据前面的内容,我们知道Handler线程通过Looper.loop方法,不断从消息队列中取出消息执行。实际上,在Message.next方法中,也会进行IdleHandler任务的插入执行。

        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;
            }
            //1
            int pendingIdleHandlerCount = -1; // -1 only during first iteration
            int nextPollTimeoutMillis = 0;
            for (;;) {
                //……
                    // 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)) {//2
                        pendingIdleHandlerCount = mIdleHandlers.size();//3
                    }
                    if (pendingIdleHandlerCount <= 0) {//4
                        // 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);//5
                }
    
                // Run the idle handlers.
                // We only ever reach this code block during the first iteration.
                for (int i = 0; i < pendingIdleHandlerCount; i++) {//6
                    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) {//7
                        synchronized (this) {
                            mIdleHandlers.remove(idler);
                        }
                    }
                }
    
                // Reset the idle handler count to 0 so we do not run them again.
                pendingIdleHandlerCount = 0;//8
    
                // 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;
            }
        }
    

    1.注释1处定义了一个pendingIdleHandlerCount变量用来记录idleHandler的数量,并且初始化时赋值-1;
    2.接着进入for循环,省略正常message的执行过程,如果当前消息等于null或者当前是一个延时消息,需要等待一段时间,就会进入idle任务的执行;
    3.首先获取mIdleHandlers的数量;
    4.如果当前没有idleHandler,进入BLOCKED状态;
    5.将mIdleHandlers中的内容拷贝到mPendingIdleHandlers中,并且维持mPendingIdleHandlers的最小容量是4;
    6.进入for循环,从mPendingIdleHandlers中取出任务并且释放该位置的对象,随后调用该idle任务的queueIdle方法;
    7.如果queueIdle方法返回false,则在mIdleHandlers中保留该任务,否则删除;
    8.所有idle任务执行完毕后将pendingIdleHandlerCount置为0,下一个循环就不会再次检查idleHandler,直到下一次next调用才会执行,保证了在idle的逻辑不会陷入死循环。

    相关文章

      网友评论

          本文标题:2020-03-08-Android的IdleHandler

          本文链接:https://www.haomeiwen.com/subject/jsordhtx.html