「Android」IdleHandler详解

「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/...

作者:山庄的铁匠原文地址:https://segmentfault.com/a/1190000043398815

%s 个评论

要回复文章请先登录注册