美文网首页
Android Looper、Message、MessageQu

Android Looper、Message、MessageQu

作者: dylanhuang88 | 来源:发表于2017-03-18 16:11 被阅读0次

概述

在Android的UI开发中,我们经常会使用Handler来控制主UI程序的界面变化,以及线程间进行通信。在面试中经常会问到相关的问题,它们到底是如何工作的呢?让我们来一探究竟。

Handler通信机制的角色

Message:消息内容,可以比喻成货品

MessageQueue:消息队列,可以比喻成货品仓库

Looper:消息分发者,可以比喻成货品管理人

Handler:消息消费者,可以比喻成接收货品的人

源码分析

首先要理解的概念是,一个线程对应一个唯一的Looper和MessagQueue,可以有多个Handler。

现在来分析它们是如何工作的:

1. Looper

整个消息机制要使用前发须执行Looper的prepare()和loop()两个函数,Activity中我们可以直接使用Handler是因为系统已经帮我们执行了,但在线程中需要我们手动执行这两个函数。下面我们来看看这两个函数的具体内容:

private static void prepare(boolean quitAllowed) {
        // sThreadLocal指向的是调用Looper的线程,这里进行了一个判断,如果通过get()方法获取到的Looper对象不对空,则报错,即一个线程只能对应一个Looper
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        // 这里是new一个Looper set到sThreadLoca里,进行了一个线程和Looper的绑定
        sThreadLocal.set(new Looper(quitAllowed));
    }

由以上代码可以看出,其实prepare()是一个创建Looper,进行线程和Looper绑定的过程,只能执行一次,不能重复创建绑定。

再来看看loop()函数

public static void loop() {
        // myLooper()是从sThreadLocal里获取刚才在prepare()里绑定的Looper对象
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        // 从Looper中获取消息队列,每一个Looper对应一个MessagQueue对象
        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();

        // 这里通过一个循环不断去取MessagQueue里的消息进行处理
        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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            // 获取到消息后调用消息里target对象进行分发message,这个target对象就是Handler,是在handler发消息时进行了设置,把handler放到message里的target中,后面会在代码中提到。
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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);
            }
            
            // 这里对message对象进行回收,因为message是使用了享元模式,避免生成过多的Message对象,所以这里进行回收放到对象池里重复利用。
            msg.recycleUnchecked();
        }
    }

2. Handler

handler相信大家都有用过,直接看看构造函数

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        // handler把当前线程绑定的looper对象赋值给mLooper了,所以默认是在当前线程进行消息分发处理的
        // 当然Looper里有一个getMainLooper()方法,可以获取到Application的Looper对象,即UI线程的Looper对象。
        mLooper = Looper.myLooper();
        // 这里进行了为空的判断,说明创建Handler使用时必须先创建Looper,调用prepare()函数
        // 所以我们在线程中要使用Handler通信时,要先调用Looper.prepare()才能创建Handler。创建完Handler再调用Looper.loop()进行消息分发处理。
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

再来看一个指定Looper的构造函数,上面的构造函数是用当前线程绑定的Looper进行消息分发的,这个构造函数可以指定Looper

    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

现在来看下发消息的处理,所有的发消息函数都会调用下面sendMessageAtTime函数,这里会调用的enqueueMessage函数中,对

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        // 把消息加入到消息队列中
        return enqueueMessage(queue, msg, uptimeMillis);
    }
    
  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        // 刚才说的target就是在这里赋值的,把当有Handler对象放到target里,那Looper中就是调用msg.target.dispatchMessage(msg)时行分发的。
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

Looper中调用msg.target.dispatchMessage(msg)时行分发,我们来看下dispatchMessage函数的源码。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

函数中就调用了handleMessage方法,就是我们创建Handler时传入的消息处理回调。

总结

最后再简单说一下整个流程:

  1. 创建Looper,建立线程和Looper、MessageQueue的一一对应关系
  2. handler调用sendMessage(msg)实际是把msg加入到消息队列中
  3. Looper一直在不断在循环取消息,有消息就调用消息的msg.target.dispatchMessage()方法,而dispatchMessage方法就会触发handler里的handleMessage回调,以此完成消息的传递。

相关文章

网友评论

      本文标题:Android Looper、Message、MessageQu

      本文链接:https://www.haomeiwen.com/subject/ivounttx.html