湖畔镇

Handler机制

Handler

Handler是Android中常用的线程间通信机制

Android是不允许在UI线程进行耗时的网络操作,所以一般会在工作线程中执行网络请求,得到返回数据后通知UI线程更新界面,这就可以通过Handler实现

流程分析

Handler

首先需要创建一个Handler,所以先看一下Handler的构造函数,Handler有几个版本的构造函数

Handler.java

1
2
3
4
5
6
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

这个构造函数接受三个参数,第一个指定对应的Looper,第二个指定全局的回调函数,第三个指定是同步还是异步

Handler.java

1
2
3
4
5
6
7
8
9
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;
}

这个构造函数接受两个参数,没有传入Looper,Looper在构造函数中由Looper.myLooper()创建

当mLooper为空时会抛出一个常见的异常,说明在创建Handler之前必须调用Looper.prepare()

由此我们获得了消息循环mLooper,消息队列mQueue,全局回调mCallback

Looper

Looper.java

1
2
3
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

myLooper()返回了当前线程的一个Looper

Looper.java

1
2
3
4
5
6
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是在prepare()里创建的,如果反复调用则会抛异常,意思是一个线程只能有一个Looper

Looper.java

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

Looper的构造函数里,创建了一个消息队列mQueue,并把当前的线程设置给mThread

MessageQueue

MessageQueue.java

1
2
3
4
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}

消息队列的构造函数,可见调用了Native层的相关函数nativeInit()

Message

定义了一个消息,包含了描述和可被发送给Handler的数据对象,这个对象包含两个额外的int域和一个额外的object域,允许你在很多场合不用做内存分配

尽管构造函数是public的,最好的方式是obtain()或者obtainMessage(),将从一个回收对象的池中获得对象

1
2
3
4
5
6
7
8
9
10
11
12
13
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0;
sPoolSize--;
return m;
}
}
return new Message();
}

Message里面有一个next的Message域,整个就是一个链式结构
所以sPool也是一个消息池的链,在从池中取出sPool这个消息时,sPool本身被赋值为sPool.next,池大小减1

1
private static final int MAX_POOL_SIZE = 50;

发送消息

一般通过sendMessage()这系列的函数发送消息,都要获得一个Message,设置消息类型和内容,立即或延时发送消息,最终是调用sendMessageAtTime()

Handler.java

1
2
3
4
5
6
7
8
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}

检查是否有消息队列,没有的话会抛异常,然后调用enqueueMessage()把消息放入队列

Handler.java

1
2
3
4
5
6
7
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

首先设置了消息的target字段为本Handler,然后调用MessageQueue的queueMessage()方法

enqueueMessage()放进队列的消息的target都被设置了值,而后面有判断target为空的地方

MessageQueue里有一个postSyncBarrier()方法,用来添加一个同步屏障

消息分为同步和异步,同步屏障说明之后的同步消息不被处理,异步消息就不会被影响,Handler的默认构造设置mAsynchronousfalse,即都是同步消息

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
private int postSyncBarrier(long when) {
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
msg.arg1 = token;

Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
if (prev != null) {
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}

可以发现没有设置消息的target字段,即为空,

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
boolean enqueueMessage(Message msg, long when) {
// 检查Message,目标不能为空,也不能在使用中
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) {
// 如果正在退出 就回收掉Message并返回
if (mQuitting) {
IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");
msg.recycle();
return false;
}

// 标记Message为使用中 设置触发时间字段when
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 {
// 把Message插入到队列里合适的地方
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;
}

处理消息

Looper在prepare()之后,需要调用loop()来开始消息循环

Looper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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) {
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}

开始一个无限循环,调用next()获得消息队列的下一条消息,这里可能阻塞,如果取得的消息为空则退出循环,否则获得target字段,调用其dispatchMessage()方法

Handler.java

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

按如下顺序调用回调处理消息:

1.消息中设置的回调

2.全局回调的handleMessage()

3.Handler.handleMessage(),由子类实现

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
Message next() {
// mPtr是Native层中用到的,通过nativeInit()获得,应是队列头
final long ptr = mPtr;
if (ptr == 0) {
return null;
}

int pendingIdleHandlerCount = -1;
int nextPollTimeoutMillis = 0;
// 然后开始一个无限循环,通过nativePollOnce()取一个消息
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
// 如果消息的target为空 则寻找下一个异步消息
// 说明这是一个同步屏障 不会继续处理同步消息
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}

if (msg != null) {
if (now < msg.when) {
// 消息的触发时间还没到 设置一个超时当它就绪时唤醒
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 消息就绪 标记为没有阻塞
// 从队列中取出这个消息并返回
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
msg.markInUse();
return msg;
}
} else {
nextPollTimeoutMillis = -1;
}

if (mQuitting) {
dispose();
return null;
}

// 消息队列为空或者第一条消息还没就绪 就会执行空闲Handler
if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// 没有空闲Handler 继续循环 并设置为阻塞
mBlocked = true;
continue;
}

if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}

// 运行空闲Handler 只在第一次循环的时候执行
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null;
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}

if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}

Native层实现

MessageQueue通过mPtr变量保存NativeMessageQueue对象,从而使得MessageQueue成为Java层和Native层的枢纽,既能处理上层消息,也能处理Native层消息

Handler/Looper/Message这三大类Java层与Native层并没有任何的真正关联,只是分别在Java层和Native层的Handler消息模型中具有相似的功能。都是彼此独立的,各自实现相应的逻辑

Native层分析参见这篇博客

分享