Android中个UI控件是非线程安全的, 当在子线程中进行UI更新时会强制抛出异常, 当需要更新UI时通常会借助handler发送一个Message然后再handler的handMessage方法中进行处理
Handler
构造方法
Handler的所有构造方法最终会调用下面的构造方法, 从ThreadLocal中获取Looper对象, Looper对象是通过调用Looper.prepare()方法来创建并保存的, 可以看到如果没有调用该方法创建Handler会抛出异常信息
public Handler(@Nullable Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
// 通过ThreadLocal取出和本线程相关的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
// MessageQueue为Looper中的MessageQueue
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
dispatchMessage方法
public void dispatchMessage(@NonNull Message msg) {
// message对象有callback
if (msg.callback != null) {
handleCallback(msg);
} else {
// hander对象有callback
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
sendMessageAtTime
多种通过handler发送消息的方法最终会调用handler的sendMessageAtTime方法, 可以看到最终是通过调用MessageQueue对应的enqueueMessage方法将消息加入队列
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
MessageQueue queue = mQueue; // handler内部维护的MessageQueue引用
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); // 调用enqueueMessage方法将消息插入MessageQueue中
}
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this; // handler对象(消息由谁来处理)
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis); // 通过调用MessageQueue的enqueueMessage完成消息入队
}
Message
target属性
和该Message相关的Handler对象, 该Message最终谁来处理
Looper
主线程在启动的时候回调用Looper.prepare()方法创建一个Looper并通过ThreadLocal进行保存, 并调用Looper.loop()方法进入一个消息循环中(ActivityThread类)
Looper.prepare()方法
创建Looper对象并保存到ThreadLocal
public static void prepare() {
prepare(true);
}
// 通过ThreadLocal来取, 取不到则new一个Looper通过ThreadLocal保存
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));
}
Looper的构造方法
构造方法会创建一个MessageQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper.loop() 方法(核心代码)
public static void loop() {
// 获取本线程的Looper对象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// 获取Looper对应的MessageQueue对象
final MessageQueue queue = me.mQueue;
// 消息循环
for (;;) {
// 从MessageQueue中获取一条消息
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
try {
// 将消息分发给对应的Handler进行处理
msg.target.dispatchMessage(msg);
} catch (Exception exception) {
} finally {
}
}
}
MessageQueue
消息队列, 单向链表, 通过enqueueMessage方法将Message入队, 通过next方法从队列中获取一个Message, next方法可能会阻塞, 需要在enqueueMessage方法中进行唤醒
enqueueMessage方法
boolean enqueueMessage(Message msg, long when) {
// target属性为null抛出异常
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 {
// 翻译: 插入队列的中间部分, 通常不需要唤醒, 除非在队列的头部有一个barrier
// 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;
}
同步屏障
taget为null的Message, 利用postSyncBarrier方法插入。当 MessageQueue 中遇到了一个同步屏障,则它会忽略后面的同步消息直到遇到一个异步的消息,这样设计是为了当队列中遇到同步屏障时,优先执行异步消息。
next方法
Message next() {
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;
// 发现一个栅栏, 跳过接下来的Message直到一个异步的Message
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;
}
}
阻塞唤醒机制
主线程在Looper.loop()死循环中运行, 当没有消息需要处理的时候回占用cpu资源, 这时候需要将其阻塞, 底层使用linux epoll实现, 在next中进行阻塞, 当子线程通过handler向MessageQueue中插入消息时会判断是否需要唤醒主线程