IdleHandler原理及应用

前言

最近复习Handler的源码的时候,看到MessageQueue中有一个addIdleHandler(IdleHandler handler)方法,参数需要传递一个接口IdleHandler并保存在mIdleHandlers中。

public void addIdleHandler(@NonNull IdleHandler handler) {
    
    
        if (handler == null) {
    
    
            throw new NullPointerException("Can't add a null IdleHandler");
        }
        synchronized (this) {
    
    
            mIdleHandlers.add(handler);
        }
    }
   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中没有可以处理的消息的时候回调queueIdle,接口只有一个返回值,返回false的话会从mIdleHandlers集合中删除,反之保留。

源码

我们都知道Handler处理消息的时候是通过循环调用MessageQueue.next()方法,所以我直接就看next的源码:

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;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        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;
                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());
                }
                if (msg != null) {
    
    
                    if (now < msg.when) {
    
    
                        // 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 {
    
    
                        // 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 {
    
    
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

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

                // 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.
              	// 这里才是处理IdelHandler消息的位置
              	// 第一次进入,消息队列为空或者当前的时间小于将要处理消息的目标时间
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
    
    
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
              	//mIdleHandlers中为空,阻塞
                if (pendingIdleHandlerCount <= 0) {
    
    
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }
              	//下面是将mIdleHandlers集合转化数组
                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.
          	// 遍历数组回调queueIdle()
            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);
                }

              	//判断取出的返回值为false就idler从mIdleHandlers删除
                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;
        }
    }

使用场景

以前我们在Activity中获取某个控件的宽高的时候总是得到的是0,那是因为view的测量还未完成。通常的做法是监听ViewTreeObserver,它是在ViewRootImpl测量完成之后调用ViewTreeObserver.dispatchOnGlobalLayout()方法,这时候在onGlobalLayout回调中获取的控件宽高都是正确的数据。

现在我们可以使用IdleHandler实现,在所有UI消息处理完成之后才处理IdleHandler中的消息,这样也可以正确的获取控件的宽高了,代码如下:

override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        Looper.myQueue().addIdleHandler {
    
    
            Loger.e("--Idle--${
      
      mView.width}${
      
      mView.height}----")
            false
        }
    }

猜你喜欢

转载自blog.csdn.net/ZYJWR/article/details/103086664