android源码分析:handler

1.前言

Android的消息队列机制主要由四个对象完成:

  1. Handler
  2. Looper
  3. MessageQueue
  4. ThreadLocal 线程本地存储(即ThreadLocalStorage,简称TLS)提供线程独享的Looper对象。ThreadLocal源码分析

2.源码分析

2.1Handler构造函数

Handler(Callback callback, boolean async)是Handler比较重要的构造函数实现,源码如下:

1
2
3
4
5
6
7
8
9
10
11
public Handler(Callback callback, boolean async) {//null,false
//...省去无关代码
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和Message,Queue在Handler构造时被赋值。在一个线程需要
使用Handler之前,需要调用Looper.prepare() 将一个Looper对象通过ThreadLocal.set方法存入线程的
ThreadLocalMap中,以便在实例化Handler的时候,不会抛出上面的RuntimeException。
对于Android主线程而言,在ActivityThread的main方法中实例化了主线程的MainLooper,所以在开发的过程中不
再需要主动调用主线程的Looper.prepare方法了。

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
//...省去无关代码
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

这里需要注意的一点是:ActivityThread并不是真正的Thread,其带有main(String[] args)方法,它是Android
程序启动的入口。
接下来再来看看Looper的实例化过程,即prepare方法:

1
2
3
4
5
6
7
8
9
10
11
private static void prepare(boolean quitAllowed) {//quitAllowed 主线程传入为false,而子线程为true
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
// Looper的构造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

从以上代码来看,主线程的Looper.prepareMainLooper与子线程的Looper.prepare方法只有一个quitAllowed参数的
不同,这个参数影响的是MessageQueue的属性,决定了是否允许Looper退出,对于主线程而言,该属性为false。
暂且抛开MessageQueue不谈,通过以上代码可以分析出一个很重要的知识:一个线程可以对应多个Handler,这
些Handler复用了线程一对一对应的Looper及Looper携带的MessageQueue,复用的基础是靠ThreadLocal支撑的

2.2 Looper.loop()

Looper.loop()方法在Android的消息机制中起着非常重要的作用,以下为简化的loop方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void loop() {
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block 有可能能阻塞 nativePollOnce。
if (msg == null) {
return;
}
// This must be in a local variable, in case a UI event sets the logger
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}

Looper.loop方法是个死循环,不断的从MessageQueue中取出消息并分发给Handler。
Looper.loop()方法很简单,从简化的代码上看,可以分为三步:1.MessageQueue中取出消息2.再通过
msg.target.dispatchMessage(msg);处理消息 3.最后就将msg回收了。第一步和第三部都很好理解,但是我们还需
要了解一个msg是怎么被插入和删除的,以及target指的是哪个对象。

2.3 消息的插入

对于一个线程而言,只要Looper.prepare()与loop()方法调用后,其消息机制就已经建立好了。剩下的就是通过
实例化一个Handler并利用其进行消息的发送了。

1
2
3
Message msg = new Message();//obtainMessage
msg.obj = message;
handler.sendMessage(msg);

handler可以发送两种类型的消息,Message和Runnable,本质其实都是Message,Runnable只是赋值给了Message的callback成员。
handler发送消息的方式很多,但是最终归纳起来只有三条:

  1. sendMessageDelayed(Message msg, long delayMillis) 当前时间多少秒后
  2. sendMessageAtTime(Message msg, long uptimeMillis)
  3. sendMessageAtFrontOfQueue(Message msg)

三种方法最终调用的都是enqueueMessage方法,区别仅仅在于uptimeMillis参数的不同.

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

Handler.enqueueMessage方法的操作很简单,设置msg.target属性和msg.Asynchronous属性。其中,第一点:
msg.target指向了Handler对象本身,所以当Looper从Queue中取出msg后,最终将msg交付给Handler做处理。
第二点:Asynchronous是msg是否为异步消息的标识,在一般的开发过程中使用的msg都是同步消息。
最终调用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
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) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
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; // invariant: p == prev.next
prev.next = msg;
}

// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}

MessageQueue维护的是由Message对象组成的单链表,而MessageQueue.enqueueMessage方法就是实现消息插入的地
方,一个Message对象在链表中插入的位置是由其when属性决定的。MessageQueue.enqueueMessage方法中还涉及到
一个重要的方法:nativeWake,即MessageQueue队列唤醒,它与nativePollOnce方法是相对应的。
MessageQueue是Android消息队列机制中Java层和C++层连接的纽带,大部分核心的功能都由C++来完成。

1
2
3
4
5
6
private native static long nativeInit();
private native static void nativeDestroy(long ptr);
private native void nativePollOnce(long ptr, int timeoutMillis);
private native static void nativeWake(long ptr);
private native static boolean nativeIsPolling(long ptr);
private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);

2.4 消息的取出删除

Looper.loop方法是个死循环,不断的从MessageQueue中取出消息并分发给Handler。MessageQueue.next方法就是
消息取出的实现:

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
Message next() {
//...
int pendingIdleHandlerCount = -1; // 仅仅在首次迭代过程中,该值设置为-1。
int nextPollTimeoutMillis = 0;
for (;;) {
//阻塞操作,当等待nextPollTimeoutMillis时长,或者nativeWake(mPtr)唤醒,都会结束阻塞。
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// 不断尝试的从链表中找到首个同步消息msg。
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
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) {
if (now < msg.when) {
// 消息尚未达到执行时间,重新计算nextPollTimeoutMillis,以便在下次循环中进行阻塞。
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 消息已经达到或者超过执行时间,取出消息,同时设置mBlocked为false。
//mBlocked涉及nativeWake是否执行。
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// 遍历整个链表没有消息,则设置nextPollTimeoutMillis为-1,一直等待。
nextPollTimeoutMillis = -1;
}

// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}

// 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) {
// 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.
//在该代码块执行一次过后,pendingIdleHandlerCount就被设置为0了,永远不会再运行。
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;
}
}

MessageQueue.next方法也是一个死循环,大致可以分为两部分:消息取出部分和IdleHandler执行部分,死循环
结束的标识是从链表中取出一个Message对象。
首先执行的是消息取出部分,消息取出部分涉及到一个非常重要的方法,nativePollOnce。nativePollOnce方法是
一个阻塞方法,它会等待nextPollTimeoutMillis时长,直至时间截止或被nativeWake唤醒。next方法执行后,
首先会从mMessage头引用遍历整个链表,直至找到一个同步的Message对象msg(非异步或非Barrier的)。其次,若
msg.when大于当前时间,即尚未到msg的执行时间,则重新计算做差赋值给nextPollTimeoutMillis,在下一次循环时
nativePollOnce会而等待nextPollTimeoutMillis时长;若msg.when小于当前时间,则从链表中移除该msg并结束循
环。

在一次next方法的执行过程中,在首次循环过程里,若遇到MessageQueue没有quit且需要nativePollOnce的情
况,那么MessageQueue.IdleHandler[] 中的IdleHandler均有执行queueIdle的机会。queueIdle的返回值决定了在
该方法执行后,该IdleHandler是否需要从MessageQueue.IdleHandler[]中移除。在所有的IdleHandler.queueIdle
执行过后,pendingIdleHandlerCount就被设置为0,因此在之后的整个循环等待过程中,IdleHandler.queueIdle
不会再执行了。

当msg从MessageQueue中取出后,会调用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属性是否为null,对应post(Runnale)方法,该Runnable对象会被赋值给msg.callback,若不为null,则执行run方法。
其次查看Handler本身的Callback成员是否为Null,若不为Null,则由该成员处理msg,否则交付给经常重写的handleMessage(msg)方法。

2.5 Looper.quit

在子线程中使用Looper时需要注意的是,当所有的事情完成以后,应该调用Looper.quit相关方法结束loop循环,否则会导致线程一直处于等待状态。
Looper的退出有两种方式:quit和quitSafely,最终调用的都是MessageQueue.quit(boolean safe):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}

removeAllFutureMessagesLocked:寻找msg.when大于当前时间的msg,将其包括其之后msg全部移除,若链表头结点已经大于当前时间,则执行removeAllMessagesLocked。
removeAllMessagesLocked:移除队列里所有消息。

3.最后