美文网首页Android开发Android技术知识
Android消息机制(三):Looper

Android消息机制(三):Looper

作者: 张利强 | 来源:发表于2016-04-19 15:35 被阅读356次

    Looper在Android消息机制中的主要作用就是一直循环从MessageQueue中取Message,取出Message后交给它的target,该target是一个Handler对象,消息交给Handler后通过调用Handler的dispatchMessage()方法进行处理。

    类成员

    filed 含义 说明
    sThreadLocal Looper 对象 每个线程中的Looper对象其实是一个ThreadLocal,即线程本地存储(TLS)对象
    sMainLooper 主线程使用的Looper对象 由系统在ActivityThread主线程中创建。
    mQueue 和Looper对应的消息队列 一个Looper依赖一个消息队列(一对一)
    mThread 和Looper对应的线程 一个Looper和一个线程绑定(一对一)

    Looper工作过程

    1. 为线程创建消息循环
      使用Looper对象时,会先调用静态的prepare方法或者prepareMainLooper方法来创建线程的Looper对象。如果是主线程会调用prepareMainLooper,如果是普通线程只需调用prepare方法,两者都会调用prepare(boolean quitAllowed)方法,该方法源码如下:
        /**
         * 该方法会创建Looper对象,Looper对象的构造方法中会创建一个MessageQueue对象,再将Looper对象保存到当前线程 TLS
         * @param quitAllowed
         */
        private static void prepare(boolean quitAllowed) {
            if (sThreadLocal.get() != null) {
                // 试图在有Looper的线程中再次创建Looper将抛出异常,一个线程只能有一个looper。
                throw new RuntimeException("Only one Looper may be created per thread");
            }
            // 我们调用该方法会在调用线程的TLS中创建Looper对象
            sThreadLocal.set(new Looper(quitAllowed));
        }
    

    第一次调用prepare()方法后,新创建出来的当前线程对应的Looper对象就被存储到一个TLS对象中,如果重复调用,就会报错。

    1. 开启消息循环
      Looper类乃至Android消息处理机制的核心部分,在使用Looper时,调用完Looper.prepare()后,还需要调用Looper.loop()方法开启消息循环。该方法是一个死循环会将不断重复下面的操作,直到没有消息时退出循环。

    2. 读取MessageQueue的下一条Message

    3. 把Message分发给相应的target(Handler)来处理

    4. 把分发后的Message,回收到消息池以复用

      /**
         * 在这个线程中启动队列,请确保在循环结束时候调用{@link #quit()}
         *
         * 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();//获取TLS存储的Looper对象
            if (me == null) {//如果没有调用Loop.prepare()的话,就会抛出下面这个异常
                throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
            }
            final MessageQueue queue = me.mQueue;//从Looper中取出消息队列
    
            // 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 (;;) {
                //调用MessageQueue的next方法来获取新消息,而,next是一个阻塞方法,没有消息时,loop方法将跟随next方法会一直阻塞在这里。
                Message msg = queue.next(); // might block,如果没有新消息,这里会被阻塞。
                //因为以上获取消息是阻塞方法,所以,当消息队列中没有消息时,将阻塞在上一步。而如果上一步拿到了一个空消息,只能说明
                //我们退出了该消息队列。那么这里直接退出
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                    //没有消息意味着消息队列正在退出。这也就是为什么Looper的quit()方法中只需要退出消息队列即可。
                    return;
                }
    
                // This must be in a local variable, in case a UI event sets the logger
                Printer logging = me.mLogging;//默认为null,可通过setMessageLogging()方法来指定输出,用于debug功能
                if (logging != null) {
                    logging.println(">>>>> Dispatching to " + msg.target + " " +
                            msg.callback + ": " + msg.what);
                }
    
                msg.target.dispatchMessage(msg); //msg.target就是与此线程关联的Handler对象,调用它的dispatchMessage处理消息
    
                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();//确保分发过程中identity不会损坏
                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(); //将已经处理过的消息会受到消息池
            }
        }
    

    上面代码中可以看到有logging方法,这是用于debug的,默认情况下logging == null,通过设置setMessageLogging()用来开启debug工作。

    1. 获得消息循环
      myLooper()方法用于获取当前消息循环对象。Looper对象从成员变量 sThreadLocal(线程本地存储(TLS)对象) 中获取。

    获得的Looper对象可以作为Handler的构建函数参数,将在下篇文章中说明。

    • 退出消息循环
      主要是退出消息队列:
        public void quit() {
            mQueue.quit(false);//消息移除
        }
        public void quitSafely() {
            mQueue.quit(true);
        }
    

    一些其他方法

    • Looper构造方法
      Looper在执行静态方法Looper.loop()时调用Looper的构造函数(代码见上文)。在Looper初始化时,新建了一个MessageQueue的对象保存了在成员mQueue中。Looper是依赖于一个线程和一个消息队列的。
        private Looper(boolean quitAllowed) {
            // 每个Looper对象中有它的消息队列,和它所属的线程
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
        }
    
    • prepareMainLooper()
      该方法只在主线程中调用,系统已帮我们做好,我们一般不用也不能调用。

    相关文章

      网友评论

        本文标题:Android消息机制(三):Looper

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