Android消息机制

Looper

1 . Looper是一个线程的消息循环器,默认情况下,线程中是没有 Looper的。Looper的经典用法如下:

class LooperThread extends Thread {
        public Handler mHandler;
        public void run() {
           Looper.prepare();
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // todo
                }
            };

            Looper.loop();
        }
    }

2 . Looper.prepre():
prepre()会调用prepre(true):

  private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

sThreadLocal是一个静态成员变量,用来存储本地线程一些变量的,这说明在同一个线程中,prepre只能被调用一次,因此一个线程中最多只能有一个 Looper 对象。同时 Looper 的构造方法是私有的,在创建一个 Looper实例时会同时创建一个与之相应的消息队列MessageQueue;

3 . Looper.loop():
loop会对消息队列(message queue)进行无限轮询,如果消息队列中有消息则进行消息的分发,分发结束后又开始下一次的轮询。可以通过调用quit()结束轮询。

    public static void loop() {
    //从刚刚那个sThreadLocal中取出Looper对象
        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;

        //就是用来保证当前线程是否被篡改
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        //开始消息的轮询
        for (;;) {
        //如果没有消息了,会Block住,queue.mBlocked=ture
            Message msg = queue.next(); 
            if (msg == null) {
                return;
            }

         //****************省略部分代码****************
            try {
            //消息分发
                msg.target.dispatchMessage(msg);
            } finally {
         //****************省略部分代码****************
            }

            //如果分发消息过程中线程被篡改则打印些提示 log
            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();
        }
    }

在消息的分发过程中,调用的是msg.target.dispatchMessage(msg),这里的 target 对象其实就是发出iith消息的那个 Handler 对象,下面来看看Handler.sendEmptyMessage(int what)方法

Handler

1 . Handler.sendEmptyMessage(int what)
下面来看通过 Handler 发送一个消息出去的过程,所有的消息发送最后都会调用sendMessageAtTime(Message msg, long uptimeMillis):

  public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
  //mQueue 是 Handler 实例化时从 Looper 中获取的,所以与 Looper 中的是同一个。
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        //在enqueueMessage方法中会设置msg.target = this(当前 handler),并且最终会调queue.enqueueMessage(queue, msg)
        return enqueueMessage(queue, msg, uptimeMillis);
    }

2 . MessageQueue.enqueueMessage(queue, msg)

    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) {
           //****************省略部分代码****************

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
             //如是 p为空,表明消息队列中没有消息了,那么msg将是第一个消息
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //对Handler发出于默认的消息,msg.isAsynchronous()=false
                //mBlocked代表着消息队列是否被Block住了,参考 Looper.loop() 以及MessageQueue.next()
                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;
                prev.next = msg;
            }

            if (needWake) {
            //唤醒Looper
                nativeWake(mPtr);
            }
        }
        return true;
    }

3 . 消息的分发 dispatchMessage(Message msg)

  public void dispatchMessage(Message msg) {
  //msg.callback其实是创建Messag对象时传入的Runnable对象。如果传入了Runnable,则处理消息时由Runnable对象来处理,即调用 run 方法
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
        //同理,如果 mCallback不为空,则由mCallback来处理,CallBack是 Handler 中的一个接口,构建 Handler 时可传入一个全局实现
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //这就是我们平时重写的handleMessage方法
            handleMessage(msg);
        }
    }

总结

Looper,Handler,MessageQueue 三者的相互配合,构成 Andoid 系统的消息机制,其中MessageQueue作为消息的容器,而 Looper负责对 MessQueue 进行轮询,当没有消息需要处理时,就会处于 Block 状态,而 Handler 负责将消息发送到MessageQueue中,并同时负责消息的分发或者处理,处理时首先交给 Message的 callback 对象,否则交给 Handler 的 mCallback 处理,如果都没处理最后才会交给 handleMessage 方法进行处理。对于一个线程来说,最多只能有一个 Looper 以及 MessageQueue,而 handler 可以有多个;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值