引言
在Android系统中所有涉及UI元素的操作都是由消息驱动的,比如当你修改了某个View的尺寸,或者修改了TextView的文本内容,这些操作最终都会在你不知情的情况下转化成主线程消息队列中的一条消息,在该消息被处理后你的操作才会出现相应的改变。主线程的消息队列是在App进程启动时在ActivityThread的main方法中创建的,与此同时还会开启一个无限的循环不断地从队列中取出消息并处理,取消息的操作是一个阻塞操作,也就是说当队列中无消息时主线程可以休眠,当有新消息被放入消息队列时被唤醒并继续工作。这个流程构成了Android消息系统的核心。
核心概念
从上面的描述中,我们可以提炼几个关键概念:消息队列、消息、循环、处理。其实单单从名字来看,我们也不难想象它们是如何一起构成一个可以运行的系统的,消息会被插入消息队列尾部,而循环会不停地再从队列头部取出消息然后对它进行处理。这几个词在Android系统中对应的设计分别为:MessageQueue、Message、Looper、Handler。我们先通过一段代码看看它们是如何被创建并开始工作的。
// ActivityThread.java
public static void main(String[] args) {
...
//只保留我们关心的内容
//创建Looper,并创建MessageQueue
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
// End of event ActivityThreadMain.
//开启循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
上面的代码片段很简单,它是ActivityThread的main方法,即所有App进程启动的入口方法,从该片段中我们大致可以了解到它创建了一个Looper然后开启了循环,基本符合我们最初的猜想,只不过还没有消息处理的身影,不要着急,接下来我们再一探究竟。
Looper
从ActivityThread的main方法中我们先是看到了Looper的身影,从名字看我们大概知道Looper是一个循环,接下来就以Looper为切入点看看这个循环是如何在消息系统中工作的。
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
从上面的代码中我们可以看出,prepareMainLooper其实就是创建了一个不允许退出的Looper,然后创建了消息队列以及记录了创建该Looper的线程。构造方法中传入的变量大家不必关心,只是在MessageQueue的退出方法中根据这个变量做个检查而已。
至此,Looper已经创建出来,接下来我们看看Looper在开启时做了些什么事情。
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;
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
msg.recycleUnchecked();
}
}
loop()
方法的逻辑也比较清晰,只是在for循环中不断的取出消息然后交给msg的target(这个target就是Handler实例)来处理。注意取消息的注释(might block),也就是说这里的操作可能会block,block的原因是为了在没有消息处理时进行休眠等待从而减少能耗。其实现利用了linux的select/poll机制,涉及内容较多,感兴趣的同学可以看下Gityuan的博文源码解读poll/select内核机制。
Looper的for循环还有一个延伸知识点--为什么Looper里的死循环不会卡死主线程,这个问题可能曾经或仍在困扰着部分开发者。其实从前面的几个代码片段我们也能理解个大概,首先我们都知道Java程序在main方法执行完成后JVM便会结束当前进程,因此我们在Java程序中测试多线程代码时通常需要在mian方法最后插入一行代码(Thread.sleep(long)
)让进程等待测试代码运行结束后再退出。Android的进程也是运行在JVM上的,因此也是同样的道理,为了能让App进程一直存活自然不能让主线程退出,这是为什么会有for循环的原因。那为什么这个for循环不会卡死主线程呢?其实在前面的介绍中我们已经知道了,Android的主线程事件都是通过消息来处理的,那么既然for循环中在不断的处理抛到主线程消息队列中的消息,自然主线程不会卡死了。更加深入的分析可以参考Gityuan在知乎中的回答:https://www.zhihu.com/question/34652589?sort=created。
MessageQueue
MessageQueue其实就是一个存放消息的队列,负责存储消息,其核心也就是存和取,我们先来看看存操作,即消息的入队。
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) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
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;
}
插入逻辑比较清晰,分两种情况,一是队列为空,那么直接将新消息插入队列,是否需要唤醒由mBlocked
变量决定;二是队列中有消息,那么将根据新消息的执行时间找到合适位置插入,并通过mBlocked
变量以及新消息是否是异步消息来判断是否需要唤醒(注意唤醒条件中p.target == null,所有消息在入队时都会先判断target是否为null,如果为null会抛出异常。既然如此,为什么还会存在target为null的情况呢?其实有一种特殊的栅栏消息,其target为null,栅栏消息的作用是为了同步某些操作使其必须在满足一定条件时才能执行)。这里唤醒的便是取消息时因阻塞引起的休眠。
看完了消息的插入,我们再看看消息的取出逻辑。
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;
}
//idleHandler部分不做分析
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
// idleHandler部分不做分析
// 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;
}
}
从队列中取消息的操作是在C++层完成的(具体实现细节这里不做分析,感兴趣的同学可以自行查看),取出后要先判断消息的target是否为空,即判断该消息是不是栅栏消息,如果是栅栏消息则在该消息之后找到第一条异步消息,同步消息被忽略。栅栏+异步消息给Android消息机制增加了一种简单的优先级控制,异步消息的优先级要高于同步消息。ViewRootImpl便巧妙的使用了该方法来处理UI的刷新,使其优先级提高。
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
}
}
Handler
handler是用来处理消息的,从本文第一个代码段就以初露端倪,除了dispatchMessage
外,Handler还封装了发送消息的操作。在了解Handler的功能之前,我们还是先看看其构造方法吧,日常开发中我们使用最多的便是:
/**
* Use the provided {@link Looper} instead of the default one.
*
* @param looper The looper, must not be null.
*/
public Handler(Looper looper) {
this(looper, null, false);
}
/**
* Use the provided {@link Looper} instead of the default one and take a callback
* interface in which to handle messages. Also set whether the handler
* should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param looper The looper, must not be null.
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
先看看构造方法的3个参数的含义,在使用Handler时,我们必须为其提供一个Looper,否则便没有MessageQueue存储你发出的消息。Callback是一个可选参数,当你传入Callback时便不会再回调Handler自己的handleMessage
方法。async为true时,通过该Handler构建发出的消息都是异步消息,默认该值为false。
我们在日常开发中大部分情况都是使用Handler将一个Runnable post到消息队列中,或者给其增加一个延迟,也就是下面的方法:
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
/**
* Causes the Runnable r to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the thread to which this handler
* is attached.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
*
* @param r The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
其实它们最终都是调用相同的方法sendMessageAtTime
,然后调用MessageQueue的enqueueMessage
将新消息插入到消息队列中。
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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);
}
待在Looper循环中取出该消息时,再调用Handler的dispatchMessage
进行回调,这样插入消息队列的消息便得到了调度和执行。
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
总结
到这里,我们对Android消息机制的分析就结束了。通过对Android消息机制的梳理和几个核心类的分析,我们可以用下面图对Android消息机制进行一个概括性的总结。
Android消息机制.png- 1、有任务需要执行时,通过Handler将任务包装为消息发送到消息队列;
- 2、根据任务执行时间插入消息队列不同位置;
- 3、通过Looper循环将消息从队列中取出交给Handler处理;
- 4、Handler通过给定的Callback或默认方式对消息进行处理。
网友评论