Handler机制分析

最近翻译了一片关于Context泄露的文章,其中提到了Handler的一些知识点。想想当初自己研究这块的时候也是看着源码一点点抠出来的。只不过那时候没有做个总结,现在正好借着这个机会把这块知识点总结下,也算是做个备注了。

我们知道Android应用启动的时候会执行ActivityThread类的main方法,详情请参见罗升阳的这篇文章。main方法中会为主线程创建一个Looper对象,这个Looper中维护了一个消息队列MessageQueen。Looper会不断的从消息队列中取消息,然后交给消息的target对象(即Handler)去处理这个消息。如果队列中没有消息,那么Looper就会进入等待状态直到队列中有新消息。大概的过程就是这样,下面我们通过源码来了解下整个过程。

首先来看看ActivityThread的main方法,这里只保留了跟本文相关的主要代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();
thread.attach(false);

if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}

Looper.loop();
}

main方法中首先调用了Looper.prepareMainLooper()来为主线程创建一个Looper对象,然后在调用Looper.loop()方法进入一个无限循环状态不断的从消息队列中取消息进行处理。那么,我们再跟踪到Looper.prepareMainLooper()中去看看。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}

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));
}

prepareMainLooper()首先调用Looper的prepare()方法创建Looper对象,然后再把这个looper对象赋值给sMainLooper。同时在创建过程中确保了主线程只有一个Looper对象。Looper对象在创建的时候会同时创建一个MessageQueen对象,所有的消息都会存储在这个队列中。Looper也是从这个队列中取消息来进行处理的。并且,这个Looper对象的作用域为整个线程。 这样,只要是在该线程内发送的消息,都会发送到这个Looper对象的消息队列中进行处理。

1
2
3
4
 private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

main方法最后调用了Looper的loop()方法让Looper工作起来,也就是处理消息队列中的消息。

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}
}

loop()方法先拿到当前线程的Looper对象,然后再拿到Looper的MessageQueen对象。最后进入无限循环,不断的从消息队列中取出消息。然后再把消息交给这个消息的target对象进行处理。那么现在的问题就是消息是从哪里来的以及这个target对象又是谁。

一般情况下,我们会通过handler的sendMessage(msg)方法来发送一条消息。那么我们就跟踪下这个方法,看看这个消息最终被发送到哪里去了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 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;
return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//注意:这里把this(即发送消息的那个Handler对象)赋值给了消息的target对象。
//所以,在Looper.loop()方法中的target就是一个Handler对象
return queue.enqueueMessage(msg, uptimeMillis);
}

可以看到通过层层调用,最终调用了sendMessageAtTime()方法,该方法又调用了enqueueMessage()方法将方法放入一个消息队列中。那么这个消息队列又跟Looper中的消息队列有啥关系呢?我们来看看Handler是怎么创建的。

1
2
3
4
5
6
7
8
9
10
11
12
public Handler() {
this(null, false);
}

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;
}

已经很清晰明了了。当创建Handler对象的时候,首先会通过Looper.myLooper()拿到当前线程的Looper对象,然后再拿到Looper的MessageQueen对象。也就是说我们的消息是被发送到当前线程的Looper的消息队列中了。这样Looper.loop()拿到的消息就是我们发送的消息,然后再把消息交给发送这个消息的Hanlder来进行处理。即Looper.loop()中的msg.target.dispatchMessage(msg)。那么我们再来看看handler.dispatchMessage(msg)是怎么处理这个消息的。

1
2
3
4
5
6
7
8
9
10
11
12
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

我们这里暂时不关心msg的callback以及handler的mCallback。这里最终会调用handleMessage(msg)方法,那我们当然要追踪进去看看了。

1
2
public void handleMessage(Message msg) {
}

没错,是个空方法。其实这里就是我们使用Handler的时候实现我们处理消息逻辑的地方。一般我们是这么使用Handler的:

1
2
3
4
5
6
7
private static Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//处理逻辑
}
};

至此,整个Handler机制就串通了:从消息的发送到消息的处理。

如果我们在主线程中使用Handler,那我们不用去管Looper。因为,framew已经为我们的主线程创建好了Looper。但是,如果我们要在其他线程中使用Handler这套机制,那我们就需要自己去创建Looper并调用Looper.prepare(),否则就会发生异常。