Android消息机制分析
Android的消息机制主要是指Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程。这三者实际上是一个整体,只不过 我们在开发过程中比较多地接触到Handler而已。Handler的主要作用是将一个任务切换到某个指定的线程中去执行,那么Android为什么要提供这个功能呢? 或者说Android为什么需要提供在某个具体的线程中执行任务这种功能呢?这是因为Android规定访问UI只能在主线程中进行,如果在子线程中访问UI,那么程序就会抛出异常。ViewRootImpl对UI操作做了验证,这个验证工作是由ViewRootImpl的checkThread方法来完成的。
Message
现在我们来思考一个问题既然是消息机制,那么肯定是需要发送消息的,那么消息的这个类是啥,答案是Message。Message的部分结构
public final class Message implements Parcelable {
//Message的唯一标识
public int what;
//Message携带的数据
public Object obj;
//Meesage要执行的时间戳
public long when;
//下一个节点,因为Message是存储在MessageQuene之中的,而MessageQuene实际上是一个链表
public Message next;
//用于将 Runnable 包装为 Message
public Runnable callback;
//指向 Message 的发送者,同时也是 Message 的最终处理者
public Handler target;
}
MessageQueue
上面说了Message需要存储在MessageQueue之中,而MessageQueue实际上是一个链表是一个链表,那么MessageQueue是需要提供什么功能?插入消息和取消息。这里展示MessageQueue的部分代码
public final class MessageQueue {
//入队操作
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
//这里存在多线程通信,需要保证线程同步
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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;//mMessages是链表的头节点
boolean needWake;//用于标记是否需要唤醒 next 方法,因为next是一个回阻塞的方法,如果在next()阻塞的时候,插入了一条时间戳更短的消息,那么就需要优先执行这个消息,这个时候就需要唤醒休眠的线程了。
//如果没有消息,那么新消息就是链表的头节点。或者处于队头的消息的时间戳比 msg 要大,或者这个消息的时间戳为0,则将 msg 作为链表头部。
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;
//从链表头向链表尾遍历,寻找链表中第一条时间戳比 msg 大的消息,将 msg 插到该消息的前面,messageQuene中的消息都是按照时间戳的大小排序的
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) {
//唤醒next()方法
nativeWake(mPtr);
}
}
return true;
}
//next() 方法是一个无限循环的方法,如果消息队列中没有消息,则该方法会一直阻塞,当有新消息来的时候 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;
//外部可能会随时向MessageQueue发送Message,所以MessageQueue需要开启一个无限循环,反复取值,然后做处理
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//将 next 方法的调用线程休眠指定时间
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) {
//如果当前时间还未到达消息的的处理时间,也就是是一个延迟消息,那么就计算还需要等待的时间,就是这个消息要到nextPollTimeoutMillis之后才能处理
// 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;
}
}
}
MessageQueue里面的关键的两个函数就是上面,我这里面把所有的代码都列出来了,没有中文注释的地方可以暂时忽略,后面讲到的时候会重新提的。
Handler
上面提到外部可能会随时向MessageQueue发送Message,那么这个外部就是我们的Handler了。那么Handler主要就是发送消息了,和能够做线程切换了。主要包括以下功能:
- 希望除了可以发送 Message 类型的消息外还可以发送 Runnable 类型的消息。这个简单,Handler 内部将 Runnable 包装为 Message 即可
- 希望可以发送延时消息,以此来执行延时任务。这个也简单,用 Message 内部的 when 字段来标识希望任务执行时的时间戳即可
- 希望可以实现线程切换,即从子线程发送的 Message 可以在主线程被执行,反过来也一样。这个也不难,子线程可以向一个特定的 mainMessageQueue 发送消息,然后让主线程负责循环从该队列中取消息并执行即可,这样不就实现了线程切换了吗?
所以说,Message 的定义和发送是由 Handler 来完成的,但 Message 的分发则可以交由其他线程来完成
Handler 至少需要包含几个方法:用于发送 Message 和 Runnable 的方法、用来处理消息的
handleMessage
方法、用于分发消息的
dispatchMessage
方法
public class Handler {
//handler的消息队列,一个handler对应一个MessageQueue
private MessageQueue mQueue;
public Handler(MessageQueue mQueue) {
this.mQueue = mQueue;
}
//Post一个Runnable对象
public final void post(Runnable r) {
sendMessageDelayed(getPostMessage(r), 0);
}
//Post一个Runnable对象
public final void postDelayed(Runnable r, long delayMillis) {
sendMessageDelayed(getPostMessage(r), delayMillis);
}
//发送一个Message消息
public final void sendMessage(Message r) {
sendMessageDelayed(r, 0);
}
public final void sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public void sendMessageAtTime(Message msg, long uptimeMillis) {
msg.target = this;
mQueue.enqueueMessage(msg, uptimeMillis);
}
private static Message getPostMessage(Runnable r) {
Message m = new Message();
m.callback = r;
return m;
}
//由外部来重写该方法,以此来消费 Message
public void handleMessage(Message msg) {
}
//用于分发消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
msg.callback.run();
} else {
handleMessage(msg);
}
}
}
那怎么做线程切换呢?上面Message中有一个target变量,是指向Handler的,如果我们把这个Message发送到主线程的MessageQueue里面,主线程从这个MessageQueue里面取出Message后,再调用Handler的dispatchMessage,这样是不是就可以实现线程切换了呢?
那么现在问题来了,如何让Handler拿到和主线程相关的MessageQueue呢。这时候就需要Looper了。
Looper
Looper应该有什么功能呢?
-
每个 Looper 对象应该都是对应一个独有的 MessageQueue 实例和 Thread 实例,这样子线程和主线程才可以互相发送 Message 交由对方线程处理
-
Looper 内部需要开启一个无限循环,其关联的线程就负责从 MessageQueue 循环获取 Message 进行处理
-
因为主线程较为特殊,所以和主线程关联的 Looper 对象要能够被子线程直接获取到,可以考虑将其作为静态变量存着
这样,Looper 的大体框架就出来了。通过 ThreadLocal 来为不同的线程单独维护一个 Looper 实例, ,再通过
myLooper()
方法来获取和当前线程关联的 Looper 对象,和主线程关联的
sMainLooper
作为静态变量存在,方便子线程获取
public final class Looper {
//通过 ThreadLocal 来为不同的线程单独维护一个 Looper 实例
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
@UnsupportedAppUsage
private static Looper sMainLooper; // guarded by Looper.class
private static Observer sObserver;
@UnsupportedAppUsage
final MessageQueue mQueue;
final Thread mThread;
//每个线程通过prepare()方法来初始化本线程独有的 Looper 实例
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//每一个线程有自己独有的Looper
sThreadLocal.set(new Looper(quitAllowed));
}
//在ActivityThread中调用了,初始化sMainLooper
@Deprecated
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
//因为 next() 方法是一个阻塞操作,所以当没有消息也会导致 loop() 方法一只阻塞着,而当 MessageQueue 一中有了新的消息,Looper 就会及时地处理这条消息并调用 Message.target.dispatchMessage(Message) 方法将消息传回给 Handler 进行处理
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
if (me.mInLoop) {
Slog.w(TAG, "Loop again would have the queued messages be executed"
+ " before this one completed.");
}
me.mInLoop = true;
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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
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);
}
// Make sure the observer won't change while processing a transaction.
final Observer observer = sObserver;
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
try {
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
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();
}
}
}
Message:用来表示要发送的消息,执行的任务
Handler:子线程持有的 Handler 如果绑定到的是主线程的 MessageQueue 的话,那么子线程发送的 Message 就可以由主线程来消费,以此来实现线程切换,执行 UI 更新操作等目的
MessageQueue:即消息队列,通过 Handler 发送的消息并非都是立即执行的,需要先按照 Message 的优先级高低(延时时间的长短)保存到 MessageQueue 中,之后再来依次执行
Looper:Looper 用于从 MessageQueue 中循环获取 Message 并将之传递给消息处理者(即消息发送者 Handler 本身)来进行消费,每条 Message 都有个 target 变量用来指向 Handler,以此把 Message 和其处理者关联起来。不同线程之间通过互相拿到对方的 Looper 对象,以此来实现跨线程发送消息。
Handler处理消息的线程是其Looper创建的线程
,比如你在子线程创建Handler,但是用的是主线程的Looper,那么最终handlerMessage运行的线程就是再主线程。
以上就是Android消息机制的源码分析了。
消息机制的拓展
同步屏障
上面讲解了android的消息机制,下面就讲解一些拓展的只是,这些知识是我们开发中使用比较少的知识点,但是对于我们来说,对理解android的运行和原理还是有一定的帮助的。讲解同步屏障之前,我们先思考一个问题,Android的中是怎么处理屏幕刷新的消息的。如果主线程有任务,但是这个时候又有屏幕刷新的信号到来,那么应该怎么处理?我们知道屏幕刷新时android中最重要的事情,所以他是怎么做到让前面的任务不处理,优先处理刷新的任务的?答案时通过同步屏障去操作的。
那么什么时同步屏障?
Handler发送的消息分为普通消息、屏障消息、异步消息,一旦Looper在处理消息时遇到屏障消息,那么就不再处理普通的消息,而仅仅处理异步的消息。这就是同步屏障。那android绘制流程时怎么个流程呢?
调用requestLayout()方法之后,并不会马上开始进行绘制任务,而是会给主线程设置一个同步屏幕,并设置Vsync信号监听。当Vsync信号的到来,会发送一个异步消息到主线程Handler,执行我们上一步设置的绘制监听任务,并移除同步屏障。
同步屏障的代码主要是在MessageQueue中的next()中,我们可以去看一下
Message next() {
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;
//找到消息,并且target为null,说明这个消息是一个同步屏障,那么就接着找到第一个异步消息。
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());//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;
}
}
IdleHandler
IdleHandler 是 MessageQueue 的一个内部接口,可以用于在 Loop 线程处于空闲状态的时候执行一些优先级不高的操作,通过 MessageQueue 的
addIdleHandler
方法来提交要执行的操作
public static interface IdleHandler {
boolean queueIdle();
}
private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
public void removeIdleHandler(@NonNull IdleHandler handler) {
synchronized (this) {
mIdleHandlers.remove(handler);
}
}
MessageQueue 在执行
next()
方法时,如果发现当前队列是空的或者队头消息需要延迟处理的话,那么就会去尝试遍历
mIdleHandlers
来依次执行 IdleHandler
Message next() {
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
//...省略代码
//如果队头消息 mMessages 为 null 或者 mMessages 需要延迟处理
//那么就来执行 IdleHandler
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 {
//执行 IdleHandler
//如果返回 false 的话说明之后不再需要执行,那就将其移除
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;
}
}
IdleHandler在优化app启动速度的时候可以尝试去用一下。
以上就是关于Android消息机制的分析。当然Handler有很多,比如HandlerThread,IntentService之类的,这里就不展开讲了。
参考:
一文读懂 Handler 机制