Android 一起来看看面试必问的消息机制
前言
谈到 Android 的消息机制,相信大家应该不陌生,在日常开发中不可避免要接触到这方面的内容,而且这也是面试中常被问到的内容,最近本着「Read the Fucking Source Code」的原则,每天花半个小时开始看源码,从 Android 消息机制开始。本文的内容借鉴了「Android 开发艺术探索」,在此强烈向大家推荐这本书,可以说是 Android 进阶必备,质量真的相当高。
一、Android 消息机制的概述
Android 消息机制的主要是指的是 Handler 的运行机制以及 Handler 所附带的 MessageQueue 和 Looper 的工作过程,这三者实际上是一个整体,只不过我们在开发过程中比较多地接触 Handler 而已。
Handler 的主要功能是将任务切换到某个指定的线程中去执行,那么 Android 为什么要提供这个功能呢?这是因为 Android 规定访问 UI 只能在主线程中进行,如果在子线程中访问 UI,那么程序就会抛出异常。
那为什么 Android 不允许子线程中访问 UI 呢?这是因为 Android 的 UI 控件并不是线程安全的,如果在多线程中并发访问可能会导致 UI 控件处于不可预期的状态,那还有一个问题,为什么系统不对 UI 控件的访问加上锁机制呢?缺点有两个:
- 加上锁机制会让 UI 访问的逻辑变得复杂
- 锁机制会降低 UI 访问的效率,因为锁机制会阻塞某些线程的执行
Handler 创建完毕后,这个时候其内部的 Looper 以及 MessageQueue 就可以和 Handler 一起协同工作了,然后通过 Handler 的 post() 方法将一个 Runnable 投递到 Handler 的内部的 Looper 中去处理,也可以通过 Handler 的 send() 方法发送一个消息,这个消息同样会在 Looper 中去处理。其实 post() 方法最终也是通过 send() 方法来完成的。
接下来谈下 send() 的工作过程。当 Handler 的 send() 方法被调用时,它会调用 MessageQueue 的 enqueueMessage() 方法将这个消息放入消息队列中,然后 Looper 发现有新消息到来时,就会处理这个消息,最终消息中的 Runnable 或 Handler 的 handleMessage() 就会被调用。注意 Looper 是运行在创建 Handler 所在的线程中去执行的,这样一来 Handler 中的业务逻辑就被切换到创建 Handler 所在的线程中去执行了。
Android 消息机制流程图.png二、消息队列的工作原理
消息队列在 Anroid 中指的是 MessageQueue,MessageQueue 主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作,插入和删除对应的方法分别为:enqueueMessage()
和 next()
,其中 enqueueMessage()
的作用是往消息队列中插入一条消息,而 next() 的作用是从消息队列中取出一条消息并将其从消息队列中移除。尽管 MessageQueue 叫做消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息队列的,因为单链表在插入和删除上比较有优势。
接下来看下它的 enqueueMessage()
和 next()
方法的实现,enqueueMessage()
的源码如下所示:
boolean enqueueMessage(Message msg, long when) { synchronized (this) { ... 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 (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; }
可以看到 enqueueMessage()
中,主要就是进行了单链表的插入操作。
接下来看看 next()
的源码:
Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }
可以看到 next()
方法是一个无限循环的方法,如果消息队列中没有消息,那么 next()
方法会一直阻塞在这里,当有新消息到来时,next()
方法会返回这条消息并将其从消息队列中删除。
三、Looper 的工作原理
Looper 在 Android 的消息机制中扮演着消息循环的角色,具体来说就是它会不停地从 MessageQueue 中查看是否有新的消息,如果有新消息就回立刻处理,否则就一直阻塞在那里。
先来看下它的构造方法:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
在构造方法中,它会创造一个 MessageQueue 即消息队列,然后将当前的线程对象进行保存。
我们知道,Handler 的工作需要 Looper,没有 Looper 的线程就会报错,那么如何为一个线程创建 Looper 呢?其实很简单,通过 Looper.prepare()
就可以为当前线程创建一个 Looper,接着通过 Looper.loop()
来开启消息循环。
Looper 除了 prepare()
方法外,还提供了 prepareMainLooper()
方法,这个方法主要是给主线程创建 Looper 使用的,其本质也是通过 prepare()
方法来实现的。Looper 还提供了 quit()
和 quitSafely()
两个方法来退出一个 Looper,两者的区别是:quit()
会直接退出 Looper,而 quitSafely()
只是设定一个退出标识,然后把消息队列中的消息处理完毕后才安全地退出。
public void quitSafely() { mQueue.quit(true); }
Looper 最重要的一个方法是 loop()
方法,只有调用了 loop()
后,消息循环系统才会真正地起作用,Looper 的 loop()
方法的工作过程也比较好理解,loop()
方法是一个死循环,唯一跳出循环的方式是 MessageQueue 返回 null,当 Looper 的 quit()
被调用时,Looper 就会调用 MessageQueue 的 quit()
或者 quitSafely()
方法来通知消息队列退出,当前消息队列被标记为退出状态时,它的 next 方法就回返回 null。
四、Handler 的工作原理
Handler 的工作主要包括消息的发送和接收过程。消息的发送可以通过 post()
的一系列方法以及 send()
的一系列方法来实现,post()
的一系列方法最终也是通过 send()
的一系列方法来实现的。发送一条消息的典型过程如下所示。
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } 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) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
可以发现,Handler 发送消息的过程仅仅是向消息队列中插入一条消息,MessageQueue 的 next()
方法就会返回这条消息给 Looper,Looper 收到消息就开始处理,最终消息由 Looper 交给 Handler 进行处理,即 dispatchMessage()
方法会被调用,这时 Handler 就进入了处理消息的阶段,dispatchMessage() 的具体实现如下所示:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
Handler 处理消息的过程如下:
首先检查 Message 的 callback 是否为 null,不为 null,就通过 handleCallback()
来处理消息,Message 的 callback 是一个 Runnable 对象,实际上就是 Handler 的 post()
方法所传递的 Runnable 参数。handleCallback 的逻辑也比较简单,如下所示。
private static void handleCallback(Message message) { message.callback.run(); }
其次,检查 mCallback 是否为 null,不为 null 则调用 mCallback.handleMessage()
方法来处理消息。最后调用 Handler 的 handleMessage()
方法来处理消息。
总结
Android 的消息机制主要指 Handler 的运行机制,以及 Handler 所附带的 MessageQueue 和 Looper 的工作过程,三者是一个整体。当我们要将任务切换到某个指定的线程(如 UI 线程)中执行的时候,会通过 Handler 的 send(Message message msg)
和 post(Runnable r)
进行消息的发送,post()
方法最终也是通过 send()
方法来完成的。
发送的消息会插入到 MessageQueue 中(MessageQueue 虽然叫做消息队列,但是它的内部实现并不是队列,而是单链表,因为单链表在插入和删除上比较有优势),然后 Looper 通过 loop()
方法进行无限循环,判断 MessageQueue 是否有新的消息,有的话就立刻进行处理,否则就一直阻塞在那里,loop()
跳出无限循环的唯一条件是 MessageQueue 返回 null。
Looper 将处理后的消息交给 Handler 进行处理,然后 Handler 就进入了处理消息的阶段,此时便将任务切换到 Handler 所在的线程,我们的目的也就达到了。
猜你喜欢
- Android 撸起袖子,自己封装 DialogFragment
- 手把手教你从零开始做一个好看的 APP
- Android 带你撸一个好玩的 DoodleView(涂鸦)
- Android 一款十分简洁、优雅的日记 APP
更多相关文章
- Android 中LayoutInflater(布局加载器)源码篇之createViewFromTag
- Android智能指针SP WP使用方法介绍
- android绘图Paint.setXfermode()和Canvas.saveLayer()方法的作用
- Android 之采用execSQL和rawQuery方法完成数据的添删改查操作
- Android ListView 滚动的N种方法