Android 中只分主线程和工作线程,主线程不能执行耗时操作,需要创建子线程执行,但子线程不能更新UI,UI更新操作需要在主线程执行,我们开发者就常常使用Handler 去切换线程更新UI,可从本质来讲Handler不是专门用于更新UI的。Handler运行需要MessageQueue消息队列 和Looper的支撑,流程是Handler 发送消息,消息存储在消息队列(实际是一个单链表,先进先出),然后Looper轮询取出消息,然后将消息交给Handler处理。
handler使用sendMessage发送消息为入口,一步步进入发现,实际是MessageQueue在调用enqueueMessage在插入消息,先来看看这部分的源码。
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;
}
明显的可以看到在给链表插入数据时加了对象锁,多条消息同时插入时需要排队等待,然后下面就是在给链表赋值。MessageQueue既然被用来存储消息,那肯定也会有地方取消息,接着来看看它的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;
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;
}
.........................
}
}
首先进入死循环,然后加上对象锁,循环的去获取消息,找到消息则退出,否则阻塞,MessageQueue介绍完了,介绍Looper之前先来介绍ThreadLocal,它是一个线程内部存储类,通过它可以在指定的线程中存储数据,也只能在指定的线程获取数据,其他线程无法获取,ThreadLocal可以在多个线程中互不干扰的存储和修改数据,比如Looper,Looper创建时会被存入ThreadLocal,每个线程的Looper互不干扰,实际开发中ThreadLocal使用比较少,理解它有利于理解Looper。
我们在子线程使用Handler需要先创建Looper,也就是调用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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看出实际是在创建Looper ,以及创建MessageQueue,并将Looper存入ThreadLocal。然后我们来看Looper.loop()
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;
.............................
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);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
..............
msg.recycleUnchecked();
}
}
只截取了部分利于分析的代码,可以看出又是一个死循环,调用Messagequeue的next方法不停取消息,唯一跳出循环的方式时msg=null,我们知道next也是阻塞方法,没有消息会一直阻塞,只有在mQuitting变量为true时返回null,有消息时,则会使用handler处理,msg.target就是hanlder,调用它的dispatchMessage方法分发消息,dispatchMessage运行在创建Handler时所用的Looper中执行的,这样就将代码逻辑切换到指定线程中去执行。
Handler类中有很多构造方法,创建时都需要当前线程存在Looper,不然就会抛出异常,
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
经过上面的分析后,Handler就只剩消息的处理了,也就是dispatchMessage方法。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先检查Message 中callback是否null,不为null则消费消息,为null则去检查Handler中的callback接口,存在还需要去判断是否消费了,否则都会传给Hanlder中的handleMessage(msg)处理。