Android 9.0 源码_机制篇 -- 全面解析 Handler 机制(原理篇)下

本文详细探讨了Android 9.0中Handler的内部机制,包括MessageQueue的enqueueMessage和next方法,如何保证消息顺序,以及removeMessages的移除策略。总结了Handler、MessageQueue和Looper在消息传递中的角色,强调了IdleHandler在空闲时的作用,并提供了整体消息机制的图解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MessageQueue 中有两个比较重要的方法,一个是 enqueueMessage 方法,一个是 next 方法。enqueueMessage 方法用于将一个 Messag e放入到消息队列 MessageQueue 中,next 方法是从消息队列 MessageQueue 中阻塞式地取出一个 Message。在 Android 中,消息队列负责管理着顶级程序对象(Activity、BroadcastReceiver等)以及由其创建的所有窗口。

#七 创建MessageQueue

   MessageQueue(boolean quitAllowed) {
       mQuitAllowed = quitAllowed;
       // 通过 native 方法初始化消息队列,其中 mPtr 是供 native 代码使用
       mPtr = nativeInit();
   }

###next()

   Message next() {
       final long ptr = mPtr;
       if (ptr == 0) {     // 当消息循环已经退出,则直接返回
           return null;
       }

       // 循环迭代的首次为 -1
       int pendingIdleHandlerCount = -1; // -1 only during first iteration
       int nextPollTimeoutMillis = 0;
       for (;;) {
           if (nextPollTimeoutMillis != 0) {
               Binder.flushPendingCommands();
           }

           // 阻塞操作,当等待 nextPollTimeoutMillis 时长,或者消息队列被唤醒,都会返回
           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) {
                   // 当消息 Handler 为空时,查询 MessageQueue 中的下一条异步消息 msg,则退出循环
                   do {
                       prevMsg = msg;
                       msg = msg.next;
                   } while (msg != null && !msg.isAsynchronous());
               }
               if (msg != null) {
                   if (now < msg.when) {
                       // 当异步消息触发时间大于当前时间,则设置下一次轮询的超时时长
                       nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                   } else {
                       // 获取一条消息,并返回
                       mBlocked = false;
                       if (prevMsg != null) {
                           prevMsg.next = msg.next;
                       } else {
                           mMessages = msg.next;
                       }
                       msg.next = null;
                       // 设置消息的使用状态,即 flags |= FLAG_IN_USE
                       msg.markInUse();
                       // 成功地获取 MessageQueue 中的下一条即将要执行的消息
                       return msg;
                   }
               } else {
                   // 没有消息
                   nextPollTimeoutMillis = -1;
               }

               // 消息正在退出,返回null
               if (mQuitting) {
                   dispose();
                   return null;
               }

               // 当消息队列为空,或者是消息队列的第一个消息时
               if (pendingIdleHandlerCount < 0
                       && (mMessages == null || now < mMessages.when)) {
                   pendingIdleHandlerCount = mIdleHandlers.size();
               }
               if (pendingIdleHandlerCount <= 0) {
               // 没有 idle handlers 需要运行,则循环并等待
                   mBlocked = true;
                   continue;
               }

               if (mPendingIdleHandlers == null) {
                   mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
               }
               mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
           }

           // 只有第一次循环时,会运行 idle handlers,执行完成后,重置 pendingIdleHandlerCount 为 0
           for (int i = 0; i < pendingIdleHandlerCount; i++) {
               final IdleHandler idler = mPendingIdleHandlers[i];
               mPendingIdleHandlers[i] = null; // 去掉 handler 的引用

               boolean keep = false;
               try {
                   keep = idler.queueIdle();   // idle 时执行的方法
               } catch (Throwable t) {
                   Log.wtf(TAG, "IdleHandler threw exception", t);
               }

               if (!keep) {
                   synchronized (this) {
                       mIdleHandlers.remove(idler);
                   }
               }
           }

           // 重置 idle handler 个数为 0,以保证不会再次重复运行
           pendingIdleHandlerCount = 0;

           // 当调用一个空闲 handler 时,一个新 message 能够被分发,因此无需等待可以直接查询 pending message
           nextPollTimeoutMillis = 0;
       }
   }

nativePollOnce 是阻塞操作,其中 nextPollTimeoutMillis 代表下一个消息到来前,还需要等待的时长;当 nextPollTimeoutMillis = -1 时,表示消息队列中无消息,会一直等待下去。

当处于空闲时,往往会执行 IdleHandler 中的方法。当 nativePollOnce() 返回后,next() 从 mMessages 中提取一个消息。

#八 enqueueMessage()

    boolean enqueueMessage(Message msg, long when) {
        // 每一个普通 Message 必须有一个 target
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            // 正在退出时,回收 msg,加入到消息池
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // p 为 null (代表MessageQueue没有消息) 或者 msg 的触发时间是队列中最早的,则进入该该分支
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;   // 当阻塞时需要唤醒
            } else {
                // 将消息按时间顺序插入到 MessageQueue。一般地,不需要唤醒事件队列,除非
                // 消息队头存在 barrier,并且同时 Message 是队列中最早的异步消息
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // 消息没有退出,我们认为此时 mPtr != 0
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

MessageQueue 是按照 Message 触发时间的先后顺序排列的,队头的消息是将要最早触发的消息。当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证所有消息的时间顺序。

#九 removeMessages()

   void removeMessages(Handler h, int what, Object object) {
       if (h == null) {
           return;
       }

       synchronized (this) {
           Message p = mMessages;

           // 从消息队列的头部开始,移除所有符合条件的消息
           while (p != null && p.target == h && p.what == what
                  && (object == null || p.obj == object)) {
               Message n = p.next;
               mMessages = n;
               p.recycleUnchecked();
               p = n;
           }

           // 移除剩余的符合要求的消息
           while (p != null) {
               Message n = p.next;
               if (n != null) {
                   if (n.target == h && n.what == what
                       && (object == null || n.obj == object)) {
                       Message nn = n.next;
                       n.recycleUnchecked();
                       p.next = nn;
                       continue;
                   }
               }
               p = n;
           }
       }
   }

这个移除消息的方法,采用了两个 while 循环,第一个循环是从队头开始,移除符合条件的消息,第二个循环是从头部移除完连续的满足条件的消息之后,再从队列后面继续查询是否有满足条件的消息需要被移除。

#总结

最后用一张图,来表示整个消息机制:
63b637532d65d2a632369cbe8315b5bb_1460000016798930.jpg

图解:

✨ Handler通过sendMessage()发送Message到MessageQueue队列;
        ✨ Looper通过loop(),不断提取出达到触发条件的Message,并将Message交给target来处理;
        ✨ 经过dispatchMessage()后,交回给Handler的handleMessage()来进行相应地处理。
        ✨ 将Message加入MessageQueue时,处往管道写入字符,可以会唤醒loop线程;如果MessageQueue中没有Message,并处于Idle状态,则会执行IdelHandler接口中的方法,往往用于做一些清理性地工作。

####想学习更多Android知识,或者获取相关资料请加入Android技术开发交流2群:935654177。本群可免费获取Gradle,RxJava,小程序,Hybrid,移动架构,NDK,React Native,性能优化等技术教程!
面向Android中的一切实体.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值