本文主要讲的内容是:Handler、Looper和MessageQueue 的关系和它们是如何一起工作的。
一、最大的困惑
1、为什么哪里都能看到的 Handler?Handler 到底是什么?
2、为什么在 Activity 中调用 Handler.post(Runnable r) 时,可以保证 r 的 run 方法中的内容会在 UI线程 中执行?
先解决第二个问题,第一个问题也就能明白了。因此,就从 Handler 的 post 方法开始看源码。
Handler.java中
public class Handler {
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(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(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
}
可以看到,Handler.post(Runnable r) 方法,主要用到的是 mQueue 对象,即 MessageQueue 对象,最终调用了 mQueue.enqueueMessage 方法。接下来看看 mQueue 的初始化。
Handler.java中
public class Handler {
final MessageQueue mQueue;
final Looper mLooper;
final Callback mCallback;
final boolean mAsynchronous;
public Handler() {
this(null, false);
}
public Handler(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());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
}
可以看到,Handler 与 Looper 及 MessageQueue 关系密切,想要知道:为什么在 Activity 中调用 Handler.post(Runnable r) 时,可以保证 r 的 run 方法中的内容会在 UI线程 中执行,就需要了解 Handler、Looper和MessageQueue 的关系及实现机制。
二、Handler、Looper和MessageQueue 的关系及实现机制
1、定义
定义比较枯燥,可是想知道它们之间的关系,需要了解定义。
1)、Handler:A Handler allows you to send and process {@link Message} and Runnable objects associated with a thread’s {@link MessageQueue}. Each Handler instance is associated with a single thread and that thread’s message queue.
意思是:每个 Handler 都会与一个 线程中的消息队列(MessageQueue) 相关联,可以通过 Handler 向 这个线程的消息队列 中发送 Message 和 Runnable。
2)、Looper:Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call {@link #prepare} in the thread that is to run the loop, and then {@link #loop} to have it process messages until the loop is stopped. Most interaction with a message loop is through the {@link Handler} class.
意思是:Looper 是用来在 线程(thread) 中 run 一个消息循环(message loop)的。线程默认是没有消息循环的,想要有的话,需要在 线程 中调用 Looper.prepare() 方法去创建一个 循环(loop),并且调用 Looper.loop() 方法,让这个 循环(loop)开始工作(开始循环,也就是死循环),直到这个 循环(loop)被停止。一般都是通过 Handler 与 Looper 交互的。
3)、MessageQueue:Low-level class holding the list of messages to be dispatched by a {@link Looper}. Messages are not added directly to a MessageQueue, but rather through {@link Handler} objects associated with the Looper.
意思是:为 Looper 提供 消息队列 的支持。Message 是不能直接加入到 消息队列(MessageQueue)中的,但是可以通过Handler(与 Looper 相关联的Handler) 向 消息队列(MessageQueue)中添加。
2、重点:
1)、每个 Thread 最多只有一个 Looper,每个 Looper 中只有一个 MessageQueue
2)、一个 Thread 可以有多个 Handler
为了解释上面两句话,需要看下 Looper 的部分源码:
public class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
final Thread mThread;
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));
}
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;
}
}
public static Looper myLooper() {
return sThreadLocal.get();
}
public static MessageQueue myQueue() {
return myLooper().mQueue;
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
}
可以看到,Looper 类中,构造方法是 private 的,而 prepare() 和 prepareMainLooper() 这两个方法都是 public static 的。
Looper 中,只有调用 prepare() 或 prepareMainLooper() 才可以调用 Looper 的构造方法。是一个单例模式,sThreadLocal 中存着 Looper 的对象。也就保证了,一个线程中,只能有一个 Looper 对象。
并且 prepare(boolean quitAllowed) 方法中,会判断是不是已经初始化过了,如果初始化过会抛出异常,所以,不仅是单例模式,并且是只能初始化一次的单例模式。所以,保证 MessageQueue 也只会初始化一次。
因此,每个 Thread 最多只有一个 Looper 对象,每个 Looper 中只有一个 MessageQueue 对象。
接下来再看一次 Handler 的构造方法:
public class Handler {
final MessageQueue mQueue;
final Looper mLooper;
final Callback mCallback;
final boolean mAsynchronous;
public Handler(Callback callback, boolean async) {
......
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
}
Handler 的构造方法中,会调用 mLooper = Looper.myLooper(); 和 mQueue = mLooper.mQueue;
会让 mLooper 是该线程唯一的 Looper 对象,mQueue 是该线程唯一的 MessageQueue 对象。
Handler 的构造方法是 public 的,所以,只要调用 Handler 的构造方法,就可以构造出一个新的 Handler 对象。
因此,一个 Thread 可以有多个 Handler 对象,且这些 Handler对象 会把 Message 或 Runnable 都送进同一个 MessageQueue。
3、Handler、Looper和MessageQueue是如何一起工作的
总体来说,是:使用 Handler 向 MessageQueue 中送 Message 或 Runnable,然后 Looper 会不停的读取 MessageQueue 中的 Message 并且处理。
一个 app 启动以后,会启动这个 app 对应的进程,会调用 ActivityThread.main 方法。main 方法中会启动这个进程的第一个线程,也就是主线程,也就是UI线程。main 方法是通过 Looper.prepareMainLooper(); 初始化 Looper,通过 Looper.loop(); 让这个 Looper 开始工作的。
public final class ActivityThread {
public static void main(String[] args) {
.......
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
......
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
在 Activity 中,使用 Handler 时,都是向 UI 线程中的 MessageQueue 中发送消息,然后 UI线程的 Looper 会不停的处理消息。接下来的代码可以看到,Handler 怎么送 Message,Looper 怎么处理 Message的。
再看一次 Hnadler 送 Message 的代码:
public class Handler {
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
}
注意!这里调用了:msg.target = this;就把 Handler 对象,关联到 Message 对象中了。
继续看 MessageQueue 类中的实现:
public final class MessageQueue {
Message mMessages;
boolean enqueueMessage(Message msg, long when) {
......
synchronized (this) {
......
msg.when = when;
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
// 插入在链表头
msg.next = p;
mMessages = msg;
} else {
// 根据 when 的时间,插入在链表中
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
......
}
return true;
}
}
MessageQueue 中的所有消息是使用链表存储的,并且是按照时间顺序排列的。
最后看下 Looper 是如何处理消息的:
public class Looper {
public static void loop() {
final Looper me = myLooper();
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;
}
......
msg.target.dispatchMessage(msg);
......
msg.recycle();
}
}
}
可以看到,Looper 的 loop 方法中,是一个死循环,会不停的读取 MessageQueue 中的数据,而这个循环是在ActivityThread.main 方法中,调用 Looper.loop(); 时开始的。
循环过程中,只要 MessageQueue 中有数据,就会调用 msg.target.dispatchMessage(msg);其中,msg.target 就是 Handler 对象(前面让注意的地方写的)。所以,会调用 Handler 的 dispatchMessage 方法。
public class Handler {
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
// Handler 的 post 方法中,会调用该方法将 Runnable 对象放入 Message 对象中
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
}
所以,如果 msg.callback 不为空,Handler 会优先处理 msg.callback。如果 msg.callback 为空,才会调用 handleMessage 方法。
三、总结
看到这里,应该已经明白 Handler、Looper和MessageQueue 的关系和它们是如何一起工作的了。也应该明白 Handler 是个什么东西了。
有一点还是要注意,因为 Handler 对象比较容易创建,并且,Message 中,会引用 Handler 对象。所以,如果通过 Handler 送的 Message 没有被执行到的时候,Handler 对象是不会被销毁掉的。
原创文章,转载请注明出处,谢谢~