Handler-Message-Looper 源码分析
Handler 是 Android 中引入的异步消息处理机制,通常会通过如下方式使用 Handler:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21private static final class MyHandler extends Handler {
// 对Activity的弱引用
private final WeakReference<MyActivity> mActivityRef;
public MyHandler(MyActivity activity) {
mActivityRef = new WeakReference<MyActivity>(activity);
}
public void handleMessage(Message msg) {
MyActivity activity = mRef.get();
if (activity == null) {
return;
}
switch(msg.what) {
// ...
// do something
}
}
}
其中,handleMessage(Message msg) 即为异步消息处理接口,那么何时才会调用此接口呢?后面再讲。
先来看一下发送消息,通常我们会调用 Handler.sendMessage() 方法来发送消息,查看 Handler 源码:
1 | // 省略之前的调用代码,直接看核心部分 |
通过上述代码分析,可以看到我们发送的消息会进入到 MessageQueue 队列中,那么 MessageQueue 是如何管理队列的呢?
查看 MessageQueue.enqueueMessage() 代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39boolean enqueueMessage(Message msg, long when) {
// 删除部分无关代码
synchronized (this) {
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// 如果队列为空或当前消息设定的发送时间已到达,则唤醒队列
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// 否则将消息插入到队列中
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
// 通过 for 循环,将消息插入到合适的位置(根据 when 判断)
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 中,那么是如何被消费的呢?这就轮到了关键的 Looper 类。
在 Looper 中的 loop() 方法展示了如何消费消息:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48public 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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
// 1. 从 MessageQueue 中取出下一个消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// 2. 调用 Handler.dispatchMessage 消费消息
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
至此已经完成了 Handler 发送、处理消息的整个流程,有兴趣的同学可以自己阅读 MessageQueue.next() 方法,查看 MessageQueue 是如何从队列中取出消息的。