Android 中线程间通信消息机制的基本思想其实很简单:为目标线程建立一个消息循环用来“监听”消息,之后我们只要在其他线程中向目标线程发送消息就可以被目标线程接收并处理,这样就完成了两个线程之间的通信。

下面我们一步一步来分析这个机制的实现(以下源码均基于 SDK 23)。

1. 为目标线程建立一个消息循环用来“监听”消息

我们都知道 Java 中一个线程执行的入口点是它的 run() 方法(或者对应 Runable 对象的 run() 方法),我们要为目标线程建立消息循环就需要在此处进行操作,否则线程代码一下子就执行完了,结束掉了。

这时我们就需要 Looper 来完成这个工作了,从其命名我们就可以看出来它是作为一个“循环器”来使用,它可以方便地为我们的线程建立消息循环。我们在使用 Looper 的时候都是先调用 Looper.prepare() ,然后创建 Handler 作为消息处理器,最后再调用 Looper.loop() 来启动消息循环。

那么 Looper.prepare() 干了些什么事情呢,我们来看一下其源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 /** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}

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

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

其中的 sThreadLocal 是 Looper 类的静态 ThreadLocal 类对象。这里先说明一下 ThreadLocal 的作用,ThreadLocal 就是用来从当前线程对象里存取数据的一个工具类。
ThreadLocal 使用 Thread.currentThread() 来获得当前代码所在的线程对象,然后把数据存到线程对象中,get 也是从线程对象里取出来。

我们从源码可以看出来 Looper.prepare() 会向当前线程对象存放一个 Looper 对象,另外 Looper 对象在创建的时候创建一个 MessageQueue,将其以及当前线程对象作为对象成员。

再来看 Handler 的创建。

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
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}

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

/**
* Use the provided {@link Looper} instead of the default one and take a callback
* interface in which to handle messages. Also set whether the handler
* should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param looper The looper, must not be null.
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

Handler 的构造函数可以传入一个 Looper 对象,否则将会调用 Looper.myLooper() 从当前线程对象里取出前面 Looper.prepare() 存的 Looper 对象,之后 Handler 将 Looper 和 MessageQueue 作为对象成员。

最后我们就可以调用 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
48
49
50
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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;

// 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 (;;) {
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);
}

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

Looper.loop() 会从当前线程对象中把前面存的 Looper 对象以及该对象的 mMessageQueue 取出来(这里取消息是通过调用 MessageQueue 的 next() 方法来取得下一条消息),然后启动消息循环,不停地从 mMessageQueue 里取消息并分派处理,也就是会调用消息对应的 target Handler 的 dispathMessage() 方法,当然这个消息处理过程就与 Looper.loop() 在同一个线程里了。

2. 向目标线程发消息

在 Android 中我们使用 Handler 来完成的。我们从前面就知道 Handler 在创建的时候就会持有一个 MessageQueue 的引用,其实这个就是用来往 MessageQueue 里发消息用的。

当我们使用 Handler 发消息时,最后都会调用到 Handler 的 enqueueMessage() 方法。

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 将 Message 的 target 设置为自己,也就是指定了这条消息将会由自己来处理,然后将 Message 放进 MessageQueue 里面。

因为 MessageQueue 的 enqueueMessage() 方法的权限是 package level 的,我们不能直接调用,就需要通过 Handler 来把消息发到 MessageQueue 里。

所以 Handler 的作用主要有两个,一是处理消息,二是作为发消息的一个工具。

3. 总结

那么根据以上分析,我们可以得出结论:

  • 一个 Looper 对象一定对应于一个线程,一个线程最多有一个 Looper 对象

  • 一个 Message 最终由它的 target Handler 来处理

  • 一个 Message 会在持有它所被加入的 MessageQueue 的 Looper 对象对应的线程中被处理

所以如果我们在子线程中完成了耗时操作想要切换到主线程更新 UI 的时候,思路应该是:

主线程 Looper 的 MessageQueue -> 主线程 Looper -> 构造持有主线程 Looper 的 Handler(new Handler(Looper.getMainLooper())) -> 使用该 Handler 发送消息