关于android:AndroidIdleHandler详解

3次阅读

共计 6491 个字符,预计需要花费 17 分钟才能阅读完成。

「Android」IdleHandler 入门

based on Android API 28

IdleHandler,这是一种在只有 当音讯队列没有音讯时 或者是 队列中的音讯还没有到执行工夫时 才会执行的 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.
         * 返回 true,则放弃该回调;返回 false,则移除该回调
         * 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 是一个回调接口,当线程中的音讯队列将要阻塞期待音讯的时候,就会回调该接口,也就是说音讯队列中的音讯都处理完毕了,没有新的音讯了,处于闲暇状态时就会回调该接口。

源码

android.os.Looper#loop

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {final Looper me = myLooper();
        if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to" + msg.target + " " +
                        msg.callback + ":" + msg.what);
            }

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;} finally {if (traceTag != 0) {Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {if (slowDeliveryDetected) {if ((dispatchStart - msg.when) <= 10) {Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

            if (logging != null) {logging.println("<<<<< Finished to" + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + "to 0x"
                        + Long.toHexString(newIdent) + "while dispatching to"
                        + msg.target.getClass().getName() + " "
                        + msg.callback + "what=" + msg.what);
            }

            msg.recycleUnchecked();}
    }

android.os.MessageQueue#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.
                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 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 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;
        }
    }

看 MessageQueue 的源码能够发现有两处对于 IdleHandler 的申明,别离是:

  • 寄存 IdleHandler 的ArrayListmIdleHandlers
  • 寄存 IdleHandler 的 数组mPendingIdleHandlers

前面的数组,它外面放的 IdleHandler 实例都是 长期 的,也就是每次应用完(调用了 queueIdle 办法)之后,都会置空mPendingIdleHandlers[i] = null

大抵的流程是这样的:

  1. 如果本次循环 拿到的 Message 为空 ,或者 这个 Message 是一个延时的音讯而且还没到指定的触发工夫 ,那么,就认定以后的音讯队列为 闲暇状态
  2. 接着就会遍历 mPendingIdleHandlers 数组(这个数组外面的元素每次都会到 mIdleHandlers 中去拿)来 调用每一个 IdleHandler 实例的 queueIdle 办法
  3. 如果这个办法返回 false,那么这个实例就会 从 mIdleHandlers 中移除,也就是当下次队列闲暇的时候,不会持续回调它的 queueIdle 办法了

解决完 IdleHandler 后会将 nextPollTimeoutMillis 设置为 0,也就是不阻塞音讯队列,当然要留神这里执行的代码同样不能太耗时,因为它是同步执行的,如果太耗时必定会影响前面的 message 执行。

应用

在利用启动时,可能心愿把一些优先级没那么高的操作提早一点解决,个别会应用 Handler.postDelayed(Runnable r, long delayMillis) 来实现,然而又不晓得该提早多少工夫比拟适合,因为手机性能不同,有的性能较差可能须要提早较多,有的性能较好能够容许较少的延迟时间。所以在做我的项目 性能优化 的时候能够应用 IdleHandler,它 在主线程闲暇时执行工作 ,而 不影响其余工作的执行

参考

https://zhuanlan.zhihu.com/p/…

正文完
 0