Android消息机制原理详解(Looper、Handler、MessageQueue)

Android的消息机制主要是指Handler的运行机制,Handler的运行机制需要底层MessageQueue和Looper的支撑。

  • Handler:消息的执行者,也可以称之为异步任务的执行者
  • Message:消息的封装者,把异步任务,消息码Handler对象等封装成Message对象
  • MessageQueue:消息队列,用于保存当前线程的所有消息Message对象的一个列表,内部储存结构为单链表的数据结构
  • Looper:循环者,能让工作线程变成循环线程,然后从消息队列中循环读取消息
  • ThreadLocal:线程内部数据储存类,通过它可以获取每个线程的Looper,线程默认是没有Looper的,如果在线程内需要使用Handler就必须为线程创建Looper(详见 ThreadLocal工作原理)

1.MessageQueue(消息队列)的工作原理

  这里说的消息队列即为MessageQueue,主要包含插入消息和读取消息两个操作,当然读取会伴随着删除。内部实现并不是队列,其实是单链表,单链表在插入和删除上有优势。
  接下来看一下插入消息enqueueMessage
boolean enqueueMessage(Message msg, long when) {
        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) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", 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) {
                // 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 (needWak
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值