Handler机制

本篇所分析的源码为Android 28

Handler经常被用于异步消息通知延时任务处理

在子线程中处理数据后,此时需要在UI线程回显数据,在主线程创建Handler对象后,子线程通过Handler.sendMessage()方法发送到handler的处理队列中,在handleMessage()方法中做相应的处理。

延时任务通过postDelayed()方法,一定时间后执行传入的Runnable对象。

源码分析

Handler中的关键类为Looper,其提供了一个MessageQueue消息队列,无论是将要发送的message还是执行的runnable都会被封装为Meassage类压入消息队列中,Looper中通过loop()方法中的死循环,根据压入的时间或延时时间,顺序分发队列中的消息。

构建Handler

Handler.java
1
2
3
4
5
6
7
8
9
10
11
12
public Handler(Callback callback, boolean async) {

mLooper = Looper.myLooper(); // 获取当前线程中的Looper对象
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; // 获取到Looper中的队列引用
mCallback = callback;
mAsynchronous = async; // 是否异步处理消息
}

创建Looper和MessageQueue

Looper对象创建后会保存到当前线程的ThreadLocal中,而主线程ActivityThread在启动时,便创建了本线程的Looper对象。

ActivityThread.java
1
2
3
4
5
6
7
public static void main(String[] args) {
Looper.prepareMainLooper(); // 创建主线程Looper
...
ActivityThread thread = new ActivityThread();
...
Looper.loop(); // 开始死循环
}
Looper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void prepareMainLooper() {
prepare(false); // 创建Looper
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();// 将当前的looper对象记录为主线程的Looper
}
}

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设置到ThreadLocal中
}

Looper中的MessageQueue,则在Looper的构造方法中一并创建。

Looper.java
1
2
3
4
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); // 创建消息队列
mThread = Thread.currentThread();
}

通过上述步骤,主线程的Handler即可工作起来,而如果想要在子线程中使用Handler,则需要手动创建Looper,并开启循环。或者直接使用主线程的looper对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
new Thread(){   
@Override
public void run() {
Looper.prepare(); //创建当前线程的Looper
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// ...
}
};
handler.sendEmptyMessage(0);
Looper.loop(); //looper开始处理消息。
}
}.start();

MessageQueue压入消息

如果是通过post()方法传入了一个Runnale,在handler中会通过getPostMessage()方法封装为message对象。

Handler.java
1
2
3
4
5
6
7
8
9
public final boolean postDelayed(Runnable r, long delayMillis){
return sendMessageDelayed(getPostMessage(r), delayMillis); // 封装为Message对象
}

private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r; // 将Runnable设置为Message的callback参数
return m;
}

而通过sendMessage()发出的消息,最终与postDelayed()一样,都会调用到sendMessageDelayed(),最终调用到enqueueMessage()方法。

Handler.java
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
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; // 将Handler自身的引用设置到msg上,当msg的处理时间到后,会分发到该Handler中处理
if (mAsynchronous) {// 如果该Handler是异步的,
msg.setAsynchronous(true); // 则将该Handler发送的消息设置为异步消息
}
return queue.enqueueMessage(msg, uptimeMillis);// 压入消息队列中
}

最终通过调用queue.enqueueMessage()将消息加入到队列中。

MessageQueue中,消息存放是一个链表,mMessages字段为链表头,方法中传入的when字段为该message预期执行的时间,通过遍历列表,通过判断链表中已有的消息的时间,使插入新消息后,链表中的消息时间顺序由小到大。

MessageQueue.java
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
boolean 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 {
// 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; // 加入到列表中
prev.next = msg;
// 如果之前没有任务处理,进入了无限阻塞状态,则压入消息后需要唤醒线程
if (needWake) {
nativeWake(mPtr);
}
}

}
return true;
}

loop处理消息

Looper创建后,需要调用loop()方法进入死循环模式,当MessageQueue中出现了新消息,则唤醒线程,推出一个消息,交由Looper处理。

Looper.java
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
public static void loop() {
final Looper me = myLooper();
if (me == null) { // 检测线程中是否存在Looper对象
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,当存在消息后会唤醒线程,推出Message
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}

try {
msg.target.dispatchMessage(msg); // 交由send该Message的Handler处理

} catch (Exception exception) {
throw exception;
}

msg.recycleUnchecked(); // 对 Message 进行了回收
}
}

取出Message后,交由Message中的target对象处理,而这个target对象则就是在Handler.enqueueMessage()的方法中赋值的。

Handler中处理这个Message

Handler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) { // 如果是Runnable
handleCallback(msg); // 则直接run。 (message.callback.run();)
} else {
// 如果是正常的消息,则调用handleMessage方法处理。
if (mCallback != null) {
// 回调到构造Handler时传入的callback中
if (mCallback.handleMessage(msg)) {
return;
}
}
// 默认为空实现,如果有子类实现,则可以重写该方法处理消息。
handleMessage(msg);
}
}

MessageQueue推出Message机制

MessageQueue.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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();
}
// 线程休眠nextPollTimeoutMillis时间
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;
// 如果是msg.target==null则说明遇到了一个同步屏障,会优先取出异步消息
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) {
// 当下一个消息的处理时间还没到达,则计算时间差值,当下次运行至nativePollOnce,阻塞相应的时间。
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;
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;// 无消息,则会一直堵塞,等待调用nativeWake唤醒
}

// 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) {
// 如果当前没有了IdleHandler,更改阻塞标志位,在下一次循环后正式进入阻塞状态
// 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;
}
}

IdleHandlers:可以在通过addIdleHandler()方法添加监听,如果链表中没有消息后,在休眠前调用该监听,处理一些消息,MessageQueue在调用完回调后,会移除监听,在下次循环后进入阻塞状态。

同步屏障是一个target == nullmessage,作用是作为一个标志,当链头为该标志时跳过同步消息,快速处理链表中的异步消息。为了更快地响应UI刷新事件,在ViewRootImplscheduleTraversals函数中就用到了同步屏障。

MessageQueue.java
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
public int postSyncBarrier() {
return postSyncBarrier(SystemClock.uptimeMillis());
}

private int postSyncBarrier(long when) {
// Enqueue a new sync barrier token.
// We don't need to wake the queue because the purpose of a barrier is to stall it.
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain(); // 获取一个Message对象
msg.markInUse();
msg.when = when;
msg.arg1 = token;

Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {// 根据时间顺序寻找插入位置,因为when一般为当前时间,往往会插入到链表头
prev = p;
p = p.next;
}
}
if (prev != null) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}
主线程不卡顿的问题

MessageQueue中通过Linux的epoll机制,阻塞、唤醒主线程。

通过epoll_create()初始化,注册监控几个文件描述符,当调用epoll_wait()后,会进入阻塞状态,等待 IO 事件。当某个描述符就绪(读或写就绪),使得 epoll 被唤醒。若超过了设定的超时时间,同样也会被唤醒避免一直阻塞。而java层调用nativeWake时,对描述符写入1,引发更改,唤醒线程。

而在主线程阻塞时,会释放CPU资源进入休眠状态,不会消耗大量CPU资源。而当绘制消息加入消息队列后,线程唤醒,处理UI绘制,绘制后再次进入阻塞状态,并不会引发UI卡顿。而绘制消息则是由两个binder线程ApplicationThreadActivityManagerProxy发出。

Handler泄露的原因及正确写法

Activity中直接创建Handler后,因为内部类默认持有一个外部类的引用,而通过Handler发出的Message中又会设置Handler的引用。当这个Message是一个延时消息后,在队列中等待中时,当Activity关闭,因为message还持有Activity的引用,导致Acitity无法销毁,内存泄露。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static class MyHandler extends Handler { // 静态类
//创建一个弱引用持有外部类的对象
private final WeakReference<MainActivity> content;

private MyHandler(MainActivity content) {
this.content = new WeakReference<MainActivity>(content);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
MainActivity activity= content.get();
if (activity != null) {
}
}
}
HandlerThread

通过继承Thread类,在调用run方法时直接创建了Looper对象,快速地创建1个带有Looper对象的新工作线程

HandlerThread.java
1
2
3
4
5
6
7
8
9
10
11
12
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}

示例代码:

1
2
3
4
5
6
7
8
val handlerThread = HandlerThread("handlerThread")
handlerThread.start()
handler = object : Handler(handlerThread.looper) {
override fun handleMessage(msg: Message?) {
// ...
}
}

总结

  1. ActivityThread启动时,创建了主线程的Looper对象,将looper对象存放到ThreadLocal中,并调用了loop()方法进入无限循环等待消息。
  2. 在创建Looper对象时,一并创建了MessageQueue对象,并在底层注册了文件操作符的监听。
  3. 在创建Handler时,构造方法中取出当前线程ThreadLocal存放的Looper对象,如果是子线程并未提前创建Looper对象,则抛出异常。也可以通过控制async参数,使得Handler发送的消息为异步消息(优先处理需设置同步屏障)。
  4. 无论是发送Message还是Runnale,最终都会封装为Message类,然后将当前时间加上延时时间计算出执行时间,交由MessageQueue加入链表。
  5. MessageQueue按时间顺序把消息加入到链表中,如果之前链表为空,则唤醒线程。
  6. MessageQueue中如果没有消息,则一直处于无限阻塞状态,当有消息插入被唤醒,则开始判断链头的消息是不是同步屏障的标识(target==null),如果是,则一直寻找下一个异步消息,找到后推出消息到Looper处理,直到处理完异步消息,移除同步屏障。如在处理消息时,消息的执行时间未到,则通过nativePollOnce()方法将线程休眠时间差值。链表中消息完全处理完成后,则进入无限阻塞状态。
  7. Looper中从MessageQueue取出消息后,交由Message中的target对象消费消息,target就是发送该MessageHandler
  8. 最终分发到HandlerhandleMessage()方法中。

参考文章

同步屏障?阻塞唤醒?和我一起重读 Handler 源码

Android中为什么主线程不会因为Looper.loop()里的死循环卡死

作者

Hanani

发布于

2022-08-12

更新于

2022-08-16

许可协议