Handler 机制
Handler 是 android 系统上实现跨线程通信的最广泛使用的方式。
一个线程中可以有几个 Handler
- 一个线程只能创建一个 Looper,可有有多个 Handler。或者说一个线程只能创建一套完整的 Handler 通信机制。
- android 系统上所有与 main 线程通信的底层实现都是 handler 机制。
Handler 机制源码分析
发送消息 Handler#sendMessage(@NonNull Message msg) 到最终的消息处理 Handler#handleMessage(@NonNull Message msg) 形成一个完成的通信过程。
发送消息的线程可以是在 main 线程 或者 子线程。一般在子线程发送消息,到主线程处理消息。
从 Handler#sendMessage(@NonNull Message msg) 开始分析源码调用过程,下面是截取的部分源码。
// frameworks/base/core/java/android/os/Handler.java
public class Handler {
@UnsupportedAppUsage
final Looper mLooper; // Looper 对象内包含有 MessageQueue 消息队列。
final MessageQueue mQueue;
@Deprecated
public Handler() { // 这个构造方法标记了 Deprecated,基本不再使用。
this(null, false);
}
@Deprecated
public Handler(@Nullable Callback callback) { // 这个构造方法标记了 Deprecated,基本不再使用。
this(callback, false);
}
/**
* (1) 这是构造方法 1。
*
* Looper 从调用方传入,与当前 Handler 实例匹配。
*/
public Handler(@NonNull Looper looper) { // 创建 Handler 实例最常使用的构方法。
this(looper, null, false); // 调用 3 个参数的构造方法 (3)。
}
/**
* (2) 这是构造方法 2。
*/
public Handler(@NonNull Looper looper, @Nullable Callback callback) { // 这个构造方法也是被经常使用的构造。
this(looper, callback, false); // 调用 3 个参数的构造方法 (3)。
}
/**
* (3) 这是构造方法 3。
*/
@UnsupportedAppUsage
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
this(looper, callback, async, /* shared= */ false);
}
/**
* (4) 这是构造方法 4。
*/
/** @hide */
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async,
boolean shared) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
mIsShared = shared;
}
// ......
/**
* 从这个方法作为 Handler 源码分析的入口。
*
* send1 ---> send2
*/
public final boolean sendMessage(@NonNull Message msg) { // 分析入口
return sendMessageDelayed(msg, 0);
}
/**
* send2 ---> send3
*/
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
/**
* send3
*
* 调用到这里,将 msg 对象加入到消息队列。
*/
public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
// ......
}
- 从上面的源码中,
Handler()Handler(@Nullable Callback callback)已经被标记 deprecated,不再建议使用,也就是Looper的引用是从外部传入。 Looper中包含有MessageQueue,从构造方法 4 看得出来,Handler间接持有MessageQueue引用。
接下来重要的实现在于 Looper 和消息循环。
Looper 循环泵
Looper 是一个循环泵,不停地从 MessageQueue 中提取消息,并分发给目标 Handler 进行处理。
上一节 Handler 源码最后的 private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg, long uptimeMillis) 方法中,调用到 MessageQueue#enqueueMessage(Message msg, long when) 方法,它的声明 boolean enqueueMessage(Message msg, long when)。接着我们来看下 Looper 的创建和它是如何循环的。
首先需要知道一点,一个线程(Thread)默认是没有消息队列(MessageQueue)的,即也不会有消息循环这个说法。但 Android app 进程运行的主线程(main thread)中,我们都知道有消息循环机制,有 looper 进行消息循环,从消息队列(MessageQueue)中获取消息,并分发到目标 Handler 进行处理。
那么,下来就需要知道一个线程(Thread)中如何绑定一个消息循环机制。
看下面的这段代码,其中表达了:让一个线程具备消息循环的能力。
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler(Looper.myLooper()) {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
- 调用
Looper#prepare()创建消息队列。 - 调用
Looper#loop()开始消息循环。
Looper#prepare()
下面看 Looper#prepare() 相关源码。
public final class Looper {
@UnsupportedAppUsage
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
@UnsupportedAppUsage
final MessageQueue mQueue;
final Thread mThread;
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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");
}
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
// ......
}
-
if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); }首先,判断
sThreadLocal中是否已经保存有Looper实例,如果已经有了,直接抛出异常。这样做保证了 “一个线程只能有一个 Looper 对象。” 在未找到Looper实例的情况下,sTreadLocal.set(new Looper(quitAllowed))保存Looper实例。 -
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }私有的
Looper构造方法中创建了MessageQueue,并获取当前线程(Thread)对象。由于构造方法的调用在sThreadLocal.get() != null之后,也间接表达了 “一个线程只能有一个消息队列。”
Looper#loop()
public final class Looper {
// ......
/**
* If set, the looper will show a warning log if a message dispatch takes longer than this.
*/
private long mSlowDispatchThresholdMs;
/**
* If set, the looper will show a warning log if a message delivery (actual delivery time -
* post time) takes longer than this.
*/
private long mSlowDeliveryThresholdMs;
/**
* True if a message delivery takes longer than {@link #mSlowDeliveryThresholdMs}.
*/
private boolean mSlowDeliveryDetected;
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
@SuppressWarnings({"UnusedTokenOfOriginalCallingIdentity",
"ClearIdentityCallNotFollowedByTryFinally",
"ResultOfClearIdentityCallNotStoredInVariable"})
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;
// 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 = getThresholdOverride();
me.mSlowDeliveryDetected = false;
for (;;) { // 这里是消息循环的重点。
if (!loopOnce(me, ident, thresholdOverride)) {
return;
}
}
}
/**
* 下面整个方法定义中最重要的消息的分发,其他都是与 log 和性能监控有关。
*/
private static boolean loopOnce(final Looper me,
final long ident, final int thresholdOverride) {
Message msg = me.mQueue.next(); // might block ---> 这里也是接下来分析的重点。
if (msg == null) { // 在消息队列中没有需要处理的 message,结束消息循环。
// No message indicates that the message queue is quitting.
return false;
}
// 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;
final boolean hasOverride = thresholdOverride >= 0;
if (hasOverride) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0 || hasOverride)
&& (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0 || hasOverride);
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); // 向目标 Handler 分发 Message 消息。
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 (me.mSlowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
me.mSlowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
me.mSlowDeliveryDetected = 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();
return true;
}
// ......
}
myLooper()尝试获取当前线程绑定的Looper对象。若没有找到,表明当前线程没有消息队列和 looper 实例。Binder.clearCallingIdentity()是在处理一个传入的 Binder 调用时,暂时将当前线程的身份(UID 和 PID)重置为本地进程的身份,以便后续操作能以本地进程的身份进行权限检查。Message msg = me.mQueue.next();获取这个Message成为了接下来分析的重点。
消息 Message
上面 Looper 的循环,执行到 loopOnce 方法内,第一个步骤是从 MessageQueue 中获取 Message 对象。
// Looper.java
private static boolean loopOnce(final Looper me,
final long ident, final int thresholdOverride) {
Message msg = me.mQueue.next(); // might block ---> 这里也是接下来分析的重点。
if (msg == null) { // 在消息队列中没有需要处理的 message,结束消息循环。
// No message indicates that the message queue is quitting.
return false;
}
// ......
}
主要看 MessageQueue 中的实现
enqueueMessage(Message msg, long when)向消息列表加入Message——Handler#sendMessage(Message)最终调用到的位置。next()获取要处理的消息 —— 消息循环的第一个步骤就是从消息队列获取消息Message对象。
MessageQueue 源码分析
先分析消息链表中添加和获取消息对象的源码。
// ./frameworks/base/core/java/android/os/CombinedMessageQueue/MessageQueue.java
public final class MessageQueue {
@UnsupportedAppUsage
Message mMessages; // 链表的表头。
private Message mLast; // 指向链表的表尾。
private IdleHandler[] mPendingIdleHandlers;
@UnsupportedAppUsage
@SuppressWarnings("unused")
private long mPtr; // used by native code
private boolean mQuitting;
// Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.
private boolean mBlocked;
@RavenwoodRedirect
private native static long nativeInit();
@UnsupportedAppUsage
@RavenwoodRedirect
private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit(); // 调用 native 方法初始化 mPtr.
}
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) { // 没有 Handler 处理的 Message 不被接收。这里也是判断屏障消息的标志。
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) { // MessageQueue 被写时保证同步。
if (msg.isInUse()) { // 判断 Message 是否正被使用。
throw new IllegalStateException(msg + " This message is already in use.");
}
if (mQuitting) { // enqueueMessage 时,这个值 false。
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(); // 标记 Message 对象正在被使用。
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) { // 首次添加时,开始组建 Message 链接的数据结构。
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked; // 如果之前是阻塞状态,则需要唤醒
if (p == null) {
mLast = mMessages;
}
} else {
// Message is to be inserted at tail or middle of 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();
// For readability, we split this portion of the function into two blocks based on
// whether tail tracking is enabled. This has a minor implication for the case
// where tail tracking is disabled. See the comment below.
if (Flags.messageQueueTailTracking()) { // 这个判断条件在构建过程中根据配置生成。
if (when >= mLast.when) { // 时间上后传入的 message 对象。
needWake = needWake && mAsyncMessageCount == 0;
msg.next = null; // 在链接中新增 message 对象。
mLast.next = msg;
mLast = msg;
} else {
// Inserted within the middle of the queue.
Message prev;
for (;;) { // 从表头开始后向查询。
prev = p;
p = p.next;
if (p == null || when < p.when) {
break; // 找到链接最后或者找到时间上的比 when 参数大的 Message 对象节点。按时间排队。
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
} // end for
if (p == null) { // 链接中到 tail 一直没找到,直接在 tail 后边添加。
/* Inserting at tail of queue */
mLast = msg;
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
} else {
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;
/*
* If this block is executing then we have a build without tail tracking -
* specifically: Flags.messageQueueTailTracking() == false. This is determined
* at build time so the flag won't change on us during runtime.
*
* Since we don't want to pepper the code with extra checks, we only check
* for tail tracking when we might use mLast. Otherwise, we continue to update
* mLast as the tail of the list.
*
* In this case however we are not maintaining mLast correctly. Since we never
* use it, this is fine. However, we run the risk of leaking a reference.
* So set mLast to null in this case to avoid any Message leaks. The other
* sites will never use the value so we are safe against null pointer derefs.
*/
mLast = null;
}
}
if (msg.isAsynchronous()) { // 判定并统计异步消息数量。
mAsyncMessageCount++;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
@UnsupportedAppUsage
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; // MessageQueue 构造时完成 mPtr 的初始化。
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// 尝试轮询一次。这个 native 调用,当没有消息的时候,当前线程进入休眠状态,出让 CPU 资源。
// 实现等待和阻塞的真正实现是 native 代码中的 epoll_wait() 系统调用,等待有事件来唤醒线程继续执行。
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) { // 当遇到一个屏障消息(Message target=null)。
// Stalled by a barrier. Find the next asynchronous message in the queue.
do { // 铆定当前 target=null 的 message,接着往后遍历,找到第一个 asynchronous=true 的 message 对象作优先处理。
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;
if (prevMsg.next == null) {
mLast = prevMsg;
}
} else {
mMessages = msg.next;
if (msg.next == null) { // 当前 message 是最后一个节点。
mLast = null;
}
}
msg.next = null; // 从 message 链表中取出 msg 实例。
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse(); // 标记 message 对象正在使用标志位 FLAG_IN_USE.
if (msg.isAsynchronous()) {
mAsyncMessageCount--;
}
if (TRACE) {
Trace.setCounter("MQ.Delivered", mMessagesDelivered.incrementAndGet());
}
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 对象。
// 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);
} // end synchronized (this)
// 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;
} // end for(;;)
}
}
// ./frameworks/base/core/jni/android_os_MessageQueue.cpp
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
if (!nativeMessageQueue) {
jniThrowRuntimeException(env, "Unable to allocate native queue");
return 0;
}
nativeMessageQueue->incStrong(env);
return reinterpret_cast<jlong>(nativeMessageQueue);
}
Message 对象可以有
- 同步消息——普通任务消息。
- 异步消息——asynchronous 属性 true 的消息。
- 屏障消息——发生在系统内主线程上,普通 app 不能使用的消息类型。
我们主要需要了解的是屏障消息。
屏障消息
屏障消息的核心是一个 Handler 的 target 为 null 的特殊 Message 对象,它相当于在消息队列中设置了一个路障。当 Looper 在 MessageQueue.next() 中轮询到这个特殊消息时,会识别出它并非需要分发的普通消息,从而触发屏障逻辑 —— Looper 会暂停处理该屏障之后的所有普通消息,转而去寻找并优先处理异步消息(isAsynchronous=true),直到屏障被显式移除。
屏障消息与普通消息的区别
下面的表格清晰展示了屏障消息与普通(同步)消息在关键属性上的差异:
| 特性 | 普通消息 (同步消息) | 屏障消息 (同步屏障) |
|---|---|---|
关键标识 target | 持有目标 Handler 的引用 (target != null) | target 为 null |
| 主要作用 | 携带任务,交由指定 Handler 处理 | 作为一个“路障”,控制消息队列的调度优先级 |
| 处理方式 | 被 Looper 取出,调用 target.dispatchMessage() 处理 | 不被 Looper 直接处理,触发屏障逻辑后,继续遍历队列 |
| 创建方式 | 通过 Handler 的 sendMessage 系列方法 | 通过 MessageQueue.postSyncBarrier() 方法(此方法为 @hide,普通应用无法直接调用) |
**屏障消息发生的线程和场景 **
消息屏障机制主要发生在主线程 (UI Thread)。
在自定义的线程中,即使自定义创建了消息循环,消息屏障也绝不会自动出现。因为 postSyncBarrier() 方法被标记为 @hide,它专供系统内部使用,且主要由 ViewRootImpl 等系统核心组件调用,以确保 UI 绘制等关键任务的优先级。
开发者无法通过常规手段在你的线程中插入屏障消息。
该机制在系统中的核心应用是确保 UI 绘制 的高优先级。其流程如下:
- 设置屏障:当一个 View 请求重绘时,
ViewRootImpl.scheduleTraversals()方法会向主线程的消息队列发送一个同步屏障。 - 发送异步绘制任务:紧接着,它将一个 UI 绘制任务包装成异步消息投递到消息队列中。
- 优先执行:当
Looper处理到同步屏障时,会跳过所有普通(同步)消息,优先执行到这个异步的绘制任务 (mTraversalRunnable)。 - 移除屏障:在绘制任务执行时,首要操作就是移除同步屏障,以恢复消息队列的正常处理顺序。
这个机制确保了 UI 绘制指令能够迅速被处理,避免被其他用户操作或回调产生的普通消息阻塞,从而防止界面卡顿或掉帧。
屏障的添加与移除
添加与移除消息屏障是系统控制的成对操作,以下是其核心步骤:
- 添加屏障 (
postSyncBarrier)
MessageQueue.postSyncBarrier()方法负责插入屏障消息:- 创建特殊消息:从消息池中获取
Message对象。它设置了when时间戳,并用arg1字段存储一个唯一的token,但关键之处在于没有设置target字段,使其成为一个屏障。 - 按时间排序:为了不阻塞已到期的任务,屏障消息会根据其
when值,被插入到消息队列中所有同时刻或更早的消息之后。 - 返回
token:方法最终会返回一个int类型的token,这就像是移除屏障的“钥匙”,必须被妥善保存。
- 创建特殊消息:从消息池中获取
- 移除屏障 (
removeSyncBarrier)
使用屏障后必须将其移除,否则队列将被永久阻塞,可能引发ANR。MessageQueue.removeSyncBarrier(int token)方法负责移除操作:- 遍历查找:根据传入的
token,在消息队列中遍历查找target为null且arg1值匹配的屏障消息。 - 从链表移除:找到目标后,将其从链表中移除。
- 按需唤醒:如果当前有线程因屏障而阻塞,移除屏障后可能需要唤醒该线程,以继续处理被搁置的同步消息。
- 遍历查找:根据传入的
消息队列(MessageQueue)
MessageQueue 的核心是一个按 when(执行时间)排序的单向链表。它的实现主要围绕三个关键操作:enqueueMessage(入队)、next(出队)和 quit(退出)。
enqueueMessage 入队的核心就是按时间排序的单向链表插入操作,保证了紧急的消息能优先被处理。
next 核心流程要点:
- 进入阻塞:调用
nativePollOnce,利用 Linux 的epoll机制让线程进入休眠,释放 CPU。 - 检查同步屏障:在处理消息前,先检查队首是否为屏障(
target == null),若是则优先寻找异步消息。 - 检查执行时间:若队首消息的
when未到,则计算等待时长,继续阻塞。 - 返回就绪消息:若
when <= now,则将消息从链表中摘除,返回给Looper。
还有一些细节慢慢更新~~~

2298

被折叠的 条评论
为什么被折叠?



