Android 消息机制之 MessageQueue 消息队列

概述

Android 消息机制主要指的是 Handler 的运行机制及其所依赖的 MessageQueue 和 Looper 的工作过程,Handler、MessageQueue、Looper组成一个相互联系的整体。本文先从 MessageQueue 的源码来说明其实现原理。

MessageQueue 原理

MessageQueue ,顾名思义,意为消息队列,其操作主要有插入和读取。插入对应的方法为 enqueueMessage(),即往消息队列中插入一条消息,而读取对应next(),该方法会从消息队列中取出一条消息并将其从消息队列中删除。虽然 MessageQueue 的名字包含队列(Queue),但是其底层实现采用的是单链表,这是因为链表在插入和删除方面的性能好。下面看其源码实现。

boolean enqueueMessage(Message msg, long when) {
       ... ...//省略
        synchronized (this) {
            if (mQuitting) {//如果中止了,直接返回
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                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;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

enqueueMessage()中,Message 对象 p 代表下一个消息,对于新进来的消息,如果满足条件: p == null || when == 0 || when < p.when,那么就将它插在消息列表的最前面;否则,就按照消息触发的时间( when 字段)来插入消息。也就是说,消息的插入是按照时间顺序从小到大进行的。

接下来在看看获取消息的 next() 方法:

Message next() 

        .....//省略
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        // 1.如果nextPollTimeoutMillis=-1,一直阻塞不会超时。
        // 2.如果nextPollTimeoutMillis=0,不会阻塞,立即返回。
        // 3.如果nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时)
        //   如果期间有程序唤醒会立即返回。
        int nextPollTimeoutMillis = 0;
        
        //死循环,但是拿到消息就return了
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            // 重要:调用到底层native的 MessageQueue
            // nextPollTimeoutMillis为-1,说明没有消息需要处理,在 native 中阻塞,
            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;
                //如果target==null,那么它就是屏障,需要循环遍历,一直往后找到第一个异步的消息
                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) {
                    //如果有消息需要处理,先判断时间有没有到,如果没到的话设置一下阻塞时间,
                    //场景如常用的postDelay
                    if (now < msg.when) {
                       //计算出离执行时间还有多久赋值给nextPollTimeoutMillis,
                       //表示nativePollOnce方法要等待nextPollTimeoutMillis时长后返回,nextPollTimeoutMillis 不为 -1
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // 获取到消息
                        mBlocked = false;
                       //链表操作,获取msg并且删除该节点 
                        if (prevMsg != null) 
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        msg.markInUse();
                        //返回拿到的消息
                        return msg;
                    }
                } else {
                    //没有消息,nextPollTimeoutMillis复位
                    nextPollTimeoutMillis = -1;
                }
                .....//省略

    }

先说一下,MessageQueue 的数据结构为一个单向链表,Message 对象有个 next 字段保存列表中的下一个,MessageQueue 中的 mMessages 保存链表的第一个元素。

可以看到,next() 是一个无限循环的方法,读取消息时如果有消息就将该消息从消息列表中移除并返回该消息,否则就一直阻塞。

参考:

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 消息机制Android 系统中用于实现组件之间通信的重要机制之一。它允许不同组件之间通过消息进行异步通信,从而实现解耦和灵活性。 Android 消息机制主要通过以下几个核心类和接口来实现: 1. Handler:它是负责发送和处理消息的类。每个 Handler 都关联一个特定的 Looper 对象,用于处理消息队列。 2. Looper:它是一个线程的消息循环器,用于不断地从消息队列中获取消息并交给对应的 Handler 处理。 3. Message:它是消息的载体,包含了要传递的数据和标识信息。 4. MessageQueue:它是消息队列,用于存储待处理的消息。 5. Runnable:它是一个接口,用于定义需要在特定时刻执行的任务。 使用消息机制可以实现不同组件之间的通信,比如在一个子线程中执行耗时操作后,可以通过 Handler 发送消息到主线程,然后由主线程的 Handler 处理该消息并更新 UI。 以下是一个简单的示例代码,演示了通过消息机制在子线程和主线程之间进行通信: ```java // 在子线程中发送消息 Thread thread = new Thread(new Runnable() { @Override public void run() { // 创建一个 Handler 对象关联当前线程的 Looper Handler handler = new Handler(Looper.myLooper()); // 创建一个消息对象 Message message = Message.obtain(); message.what = 1; message.obj = "Hello from sub thread!"; // 发送消息 handler.sendMessage(message); } }); thread.start(); // 在主线程中处理消息 Handler mainHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { if (msg.what == 1) { String text = (String) msg.obj; // 在主线程中更新 UI textView.setText(text); } } }; ``` 这段代码中,子线程通过创建一个 Handler 对象关联当前线程的 Looper,并使用 sendMessage() 方法发送消息。在主线程中,我们使用主线程的 Looper 创建了一个 Handler 对象,并通过重写 handleMessage() 方法处理收到的消息。 这只是一个简单示例,Android 消息机制还可以用于更复杂的场景,比如在不同组件之间进行通信、定时任务的调度等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值