Handler 是什么?
handler 是线程间的消息通讯机制,其主要的核心类为 Handler, Message, MessageQueue 和 Looper。
其中 Handler 是主要负责消息的处理,Message 是消息的载体, MessageQueue 为一个队列,用来维护 Message 的先后处理顺序, Looper 为线程唯一变量, 用来不断的从 MessageQueue 中获取 Message , 然后交由 Handler 进行处理。
Handler 的工作原理
以 Handler 的基本使用流程来进行分析:
Handler mHandler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
}
};
mHandler.obtainMessage().sendToTarget();
首先分析 Handler 的 obtainMessage 方法
obtainMessage 通过调用最终会使用 Message 的 obtain 方法返回 Message 对象
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
显然 Message 中维护了一个已回收的 Message 的队列, 这个队列的大小 MAX_POOL_SIZE 为 50, 如果这个回收队列为空, 才会去创建新的的 Message 对象, 因此,一半都推荐使用 obtainMessage 来获取 Message 对象,而不是直接 new 一个出来。
那么这个队列是在什么时机缓存的呢,这里先提一下, 其缓存是在 Looper 的 loop 方法中,后面会看到, 其最终调用到 Message 的 recycleUnchecked 方法。
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
sendToTarget 做了什么
public void sendToTarget() {
target.sendMessage(this);
}
target 为 Handler 对象,所以看一下 Handler 的 sendMessage 流程, 其调用 sendMessageDelayed(Message, 0) 最终调用到 sendMessageAtTime(Message,SystemClock.uptimeMillis() + delayTime), 然后调用到 MessageQueue.enqueueMessage 方法
boolean enqueueMessage(Message msg, long when) {
// 省略了一些判断
synchronized (this) {
// 调用 quit 方法后为 true 且返回 false
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;
// 根据时间插入到 MessageQueue 的对应位置
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;
}
那么唤醒操作到底唤醒了哪里呢, 答案就是 MessageQueue 的 next 方法中,
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// 调用底层方法,进行睡眠,如果传入 -1, 则无限睡眠, 直至被 nativeWake 唤醒
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
// 第一个 msg 的 target 为 null 时,表示设置了同步屏障, 优先执行异步任务
if (msg != null && msg.target == null) {
// 找到第一个异步任务
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;
}
}
}
可以看到, nativePollOnce 在两种情况下会阻塞 next 的函数,一种是
if (now < msg.when) {
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
}
此时调用 nativePollOnce 睡眠一段时间后自动唤醒继续执行。
另一种是 message 队列为 null 时, 此时 传入 nativePollOnce 的等待时间为 -1, nativePollOnce 会一直等待, 直至被 enqueueMessage 中的 nativeWake 唤醒。
next 方法在何时被调用
不难猜到 next 方法一定是在 Looper 中调用的, 因为 Looper 是作为运送者,不断的将 MessageQueue 中的 Message 运送到指定的位置进行处理, 实际上 next 是在 Looper 的 loop 方法中被调用。
public static void loop() {
// 在子线程使用 Handler 时一定要先使用 Looper.prepare 方法, 否则会抛异常
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;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// 只有当 MessageQueue 的 quit 方法调用后才可能进来
return;
}
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);
}
}
// 回收
msg.recycleUnchecked();
}
}
可以看到 loop 方法首先检查了当前线程是否有 Looper 实例:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
sThreadLocal 是一个线程独有变量, 用来确保每个线程只能持有一个当前变量, 其原理为每一个线程都有一个 ThreadLocalMap 对象, 这个 ThreadLocalMap 存储了 Entry 类型的数据, Entry 实际上就是键值对,以 ThreadLocal 为键, 要存储的值为 value. ThreadLocal 的 set 方法中,会首先判断 ThreadLocal 为键的 Entry 对象在 ThreadLocalMap 中是否存在, 如果存在,直接替换值,如果不存在, 才会去创建一个新的 Entry.
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
这样,就确保了每一个 ThreadLocal 只能存储一个 value.
而 Looper 中的 sThreadLocal 是一个静态变量,这样就可以确保,每一个线程中, 只会存在一个 Looper 对象, 否则调用 prepare 函数会抛出异常。
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));
}
接下来, loop 函数开启了一个 for(;;) 的死循环,不断的通过 MessageQueue 的 next 函数获取 message 对象,通过 Handler 的 dispatchMessage 函数进行处理。
以上就是 Handler 消息处理的基本流程。