android开发步步为营之79:通过源码分析Looper,Handler,MessageQueue之间的关系

本文深入解析了Android线程间通信的核心机制,重点介绍了Looper、MessageQueue和Handler的作用及工作原理,揭示了消息队列的先进先出原则以及消息的发送与消费流程。

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

          android线程间的通信靠什么,主要靠Looper里面的消息队列,通过看ActivityThread即所谓的UI主线程,我们可以看到里面有这么一行的代码    

final Looper mLooper = Looper.myLooper();即主线程启动的时候,默认就给我们创建了一个Looper了,我们再看看Looper.class里面有这么一段

public static MessageQueue myQueue() {
        return myLooper().mQueue;
    }

        可以知道,Looper维护了一个消息队列。那么谁往消息队列里面发送消息和取消息来消费呢?用过handler的都知道,是handler,因为我们一般这么调用的handler的发送消息的方法

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
        但是再看看Handler的源码

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
        最终是MessageQueue将message添加给了自己。那么谁又在哪里不断读取队列里面的消息呢。看看Looper的源码

/**
     * 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();

        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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(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();
        }
    }

         可以看到,其实是Looper的looper方法在无限循环的读取MessageQueue里面的Message,读取后的Message又交给了msg.target.dispatchMessage(msg);这个target就是Handler了,然后在我们创建的Handler里面处理消息

mainThreadHander = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int what = msg.what;
                //这里可以执行更新UI的操作
                if (what == 0) {
                    String content = "Thread name:" + Thread.currentThread().getName() + "'s mainThreadHander get message";
                    Log.d(TAG, content);
                    tv_content.setText(content);
                }
            }
        };

          好的,我们总结一下:主线程ActivityThread里面创建了一个Looper,Looper里面包含了MessageQueue,Handler调用MessageQueue的enqueueMessage方法,将消息发送给MessageQueue,ActivityThread里面启动了Looper.loop();Looper不断的从MessageQueue里面取消息,不断的next,即消息队列的消息是先进先出的,取出的消息交给Handler来处理。

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值