Android 的消息机制分析(三)之 Lopper 的工作原理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_29874521/article/details/81978189

在上篇文章中,我们已经介绍了消息队列里的工作原理,本文将分析 Looper 的具体实现,Looper 在 Android 的消息机制中扮演者消息循环的橘色,具体来说它会不停地从 MessageQueue 中查看是否有新信息,如果有新消息就会立即处理,否则一直阻塞在那里。首先看下他的构造方法,在构造方法中会创建一个 MessageQueue 即消息队列,然后将当前线程的消息队列保存起来,如下:

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

我们知道,Handler 的工作需要 Looper,没有 Looper 线程就会报错,那么如何为一个线程创建 Looper 呢?其实很简单,通过 Looper.prepore() 即可为当前线程创建一个 Looper,接着通过 Looper.loop() 来开启消息循环,如下所示:

        new Thread("threas1") {
            @Override
            public void run() {
                Looper.prepare();
                Handler handler = new Handler();
                Looper.loop();
            }
        }.start();

Looper 除了 prepore 方法外,还提供了 preporeMainLooper 方法,这个方法主要是给主线程也就是 ActivityThreard 创建 Looper 使用的,其本质也是通过 prepore 来实现的。由于主线程的 Looper 比较特殊,所以 Looper 提供了一个 getMainLooper 方法,通过这个方法可以在任何地方获取主线程的 Looper。Looper 也是可以退出的,Looper 提供了 quit 和 quitSafely 来退出一个 Looper,二者区别是:quit 会直接退出 Looper,而 quitSafely 只是设定一个退出标记,然后吧消息队列中的已有的消息处理完毕才安全退出。Looper 退出后,通过 Handler 发送的消息会失败,这个时候 Handler 的 send 方法返回的是 false,在子线程中,如果手动为其创建了 Looper,那么在所有的事件处理完之后应该调用 quit 方法来终止消息循环,否则这个子线程会一直处于等待状态,而如果退出 Looper 之后,这个线程就会被终止,因此建议不需要的时候终止 Looper。

Looper 最重要的一个方法是 loop 方法,只有调用了 Loop 方法,消息循环系统才会真正的起作用,它的实现如下:

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

            msg.recycleUnchecked();
        }
    }

Looper 的 Loop 方法的工作过程也很好理解,Loop 是一个死循环,唯一跳出循环的方式是 MessageQueue 的 next 方法返回了 null。当 Looper 的 quit 方法呗调用时,Looper 就会调用 MessageQueue 的 quit 或者 quitSafely 方法来通知消息队列的突出,当消息队列被标记位退出状态时,next 方法就返回了 null。也就是说,Looper 必须退出,否则 Looper 的 Loop 方法就会无限循环下去。Loop 方法会调用 MessageQueue 的 next 方法来获取新消息,而 next 方法是一个阻塞操作,当没有新消息时,next 会一直阻塞在那里,这也导致了 Loop 方法一直阻塞在那里。如果 MessageQueue 的 next 方法返回了新消息,Looper 会处理这条消息:msg.target.dispatchMessage(msg),这里的 msg.target 是发送这条消息的 Handler 对象,这样 Handler 放松的消息最终又交给它的 dispatchMessage 方法来处理。但是不同的是,这里的 Handler 的 dispatchMessage 方法是在创建 Handler 时所使用的 Looper 中执行的,这样就成功的将代码逻辑切换到指定的线程中去执行了。

炒自《开发艺术探索》

猜你喜欢

转载自blog.csdn.net/sinat_29874521/article/details/81978189