本篇分为三个部分记录Handler消息机制,第一部分逐一对“四件套”源码(基于Android-29)进行解读;第二部分根据源码总结它们之间的关联;第三部分对Handler涉及到的问题进行解答。

四件套

Message-消息

Message的作用是消息载体本身,Message类内部主要是关键参数和创建方法。官方推荐使用Mesage.obtain()或者Handler.obtainMessage()来创建Message对象,利用缓冲中Message,避免了重复创建对象。这两个方法的内法调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
@NonNull
public final Message obtainMessage()
{
return Message.obtain(this);
}

//Handler.obtainMessage()内部又调用了Message.obtain(handler)
/**
* Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
* @param h Handler to assign to the returned Message object's <em>target</em> member.
* @return A Message object from the global pool.
*/
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;

return m;
}

Handler.obtainMessage()其实是调用到了Message中的obtain()区别只是入参handler重新给message的target赋值,所以只需要关注Message.obtain(),sPool以链表形式存储了缓冲的Message对象,缓冲Message的链表不为空时就从尾部取出一个Message,为空直接创建。至于这里sPool中的Message是在什么时机缓冲起来,它其实是在looper的loop方法处理Message后调用msg.recycleUnchecked()加入到sPool缓冲池。

接下来说明Message中几个关键变量。
what是Message的唯一标示,来区分发送的Message,what值在不同handler是不需要考虑code冲突。

1
2
3
4
5
6
7
/**
* User-defined message code so that the recipient can identify
* what this message is about. Each {@link Handler} has its own name-space
* for message codes, so you do not need to worry about yours conflicting
* with other handlers.
*/
public int what;

arg1和arg2用来传递数据是int类型的数据,obj是Object类型,可以传递所有继承Object的数据类型,如果Message用在跨进程通信时obj需要进行序列化;

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
/**
* arg1 and arg2 are lower-cost alternatives to using
* {@link #setData(Bundle) setData()} if you only need to store a
* few integer values.
*/
public int arg1;

/**
* arg1 and arg2 are lower-cost alternatives to using
* {@link #setData(Bundle) setData()} if you only need to store a
* few integer values.
*/
public int arg2;

/**
* An arbitrary object to send to the recipient. When using
* {@link Messenger} to send the message across processes this can only
* be non-null if it contains a Parcelable of a framework class (not one
* implemented by the application). For other data transfer use
* {@link #setData}.
*
* <p>Note that Parcelable objects here are not supported prior to
* the {@link android.os.Build.VERSION_CODES#FROYO} release.
*/
public Object obj;

when字段表示发送消息的时间字段,基准时间是SystemClock.uptimeMillis(),如果设置了发送延时时间when的值就是基准时间加延时时间;

1
2
3
4
5
6
/**
* The targeted delivery time of this message. The time-base is
* {@link SystemClock#uptimeMillis}.
* @hide Only for use within the tests.
*/
public long when;

data类型同样用来传递数据,data是Bundle类型,可以像Activity间传递消息一样设置key-values键值对交换数据;

1
Bundle data;

target是handler的引用, target的主要作用是在Looper的loop方法中用来分发Message;

1
Runnable callback;

Message还可以设置callback参数,在消息被Looper处理时调用Message的Runnable.run(),用在Message需要一一对应不同的Runnable。

MessageQueue-消息队列维护Message链表

MessageQueue是以链表形式存储Message对象,enqueueMessage()插入对象并返回操作结果。next()主要作用是从Queue读取Message并从链表中移除,postSyncBarrier()用于在Queue中添加同步屏障。

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
boolean enqueueMessage(Message msg, long when) {
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) {
if (mQuitting) {//(1)
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}

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 {
// 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; // invariant: p == prev.next
prev.next = msg;
}

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

(1)Looper调用quit()后停止Message插入。
接下来的执行流程主要是链表的插入操作还有是否需要唤醒Looper轮询,判断依据是mBlocked(阻塞)和p.isAsynchronous()两个因素。

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
97
98
99
100
101
102
103
104
105
106
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) {(1)
return null;
}

int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}

nativePollOnce(ptr, nextPollTimeoutMillis);//(2)

synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {//(3)
// 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) {
// 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;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;//(4)
}
} else {
// No more messages.
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);
}

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

(1)Looper调用quit()后停止执行。
(2)nativePollOnce()用于“等待”消息,知道下一条Message可用为止。
(3)这里是一种同步屏障机制,target==null作为同步屏障开启的标志循环找到一个异步消息,下面的操作中优先执行异步消息。同步屏障具体深入会在后面部分说明。
(4)链表中删除目标Message并返回。
(5)MessageQueue中没有Message时执行Idlehandler(闲时机制),Idlehandler.queueIdle()返回true,Idlehandler回调会在mIdleHandlers中保持存在,false回调执行完成后从mIdleHandlers中移除。

MessageQueue.postSyncBarrier():

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
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();
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) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}

方法内部就是创建一个target为null的Message,在next方法中利用target等于null作为依据来判断是否设置同步屏障。同样对应removeSyncBarrier就是利用Message的token字段找到设置的同步屏障Message移除。

Looper-消息循环器

Looper主要职责是创建MessageQueue和处理Message。prepare方法创建looper对象添加到sThreadLocal中,Looper构造方法中同时创建MessageQueue。loop方法通过调用MessageQueue.next方法取出Message,调用msg.target的handleMessage方法交给对应handler处理Message。

prepare()和构造方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** 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()}.
*/
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) {(1
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

(1)quitAllowed 为true表示允许停止,这里构造方法是私有的,public修饰的无参构造调用这里时传入true,所以我们在日常使用中,在工作线程创建的looper都是允许停止的,只有UI线程的looper是不允许停止。也就是我们不能通过Looper.quit()来停止主线程的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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* 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();

// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);

boolean slowDeliveryDetected = false;

for (;;) {//(1)
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// Make sure the observer won't change while processing a transaction.
final Observer observer = sObserver;

final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;

if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}

final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
try {
msg.target.dispatchMessage(msg);//(2)
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();//(3)
}
}

(1)无限循环中queue调用next读取Message对象;
(2)调用hanlder.dispachMessage方法将Message交给handler处理;
(3)回收Message缓冲池未满时重置数据将Message添加到缓冲池。

Hndler-消息处理器

Hndler负责发送Message和处理回调的各种Message,enqueueMessage方法发送消息,将消息添加到queue中,handleMessage方法处理回调回来Message,Handler中的方法在开发中经常会直接使用。removeMessages方法移除当前handler下的Message,内部调用MessageQueue.removeMessages,同样的方法还有removeCallbacks()和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();

if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
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
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
public final void removeCallbacksAndMessages(@Nullable Object token) {
mQueue.removeCallbacksAndMessages(this, token);
}

//MessageQueue.removeCallbacksAndMessages
void removeCallbacksAndMessages(Handler h, Object object) {
if (h == null) {
return;
}

synchronized (this) {
Message p = mMessages;

// Remove all messages at front.
while (p != null && p.target == h
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}

// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}

hanlder中的发送Message和移除Message都是调用MessageQueue对链表做操作。

关联

上面对源码的解读,大致对各自的职责有了了解,这里对它们之间的联系做说明。

MessageQueue是以Message作为内容的链表结构,可以将Message插入到MessageQueue中,也可以将Message从MessageQueue中删除。
Looper负责循环读取MessageQueue中的Message,将Message调用给handler完成Message消息传递。
Handler负责将创建好的Message发送给MessageQueue,MessageQueue将其插入到链表中,同时Handler最终接收Looper从MessageQueue中读取的Message执行它的处理方法handleMessage。

为什么?

  • Handler消息机制的作用?
    用于跨线程通信,Android中因为UI线程不能执行耗时操作,所以需要将耗时任务在子线程执行,子线程又不能更新UI,此时就需要handler通知UI线程执行UI操作。同样子线程与子线程也可以通过Handler通信。
  • 什么是闲时机制?
    IdleHandler是一个回调接口,它存储在一个数组中,当MessageQueue中的Message任务暂时停止处理(没有新任务或者下一任务延迟在后),这个时候就会调用这个接口的queueIdle(),方法返回false则会从list中移除,返回true在下次MessageQueue暂停处理时继续调用这个接口的queueIdle方法(代码在MessageQueue.next())。
  • 什么是同步屏障?
    同步屏障就是把同步消息先屏蔽优先处理异步消息,调用MessageQueue.postSyncBarrier方法可以将一个target为空的Message插入到MessageQueue中,当Looper调用MessageQueue.next方法读取Message时首先会通过target为空来判断是否设置同步屏障,若存在,会先遍历消息链表跳过同步消息找到异步消息优先将异步消息返回给Looper执行调用。这是一种优先机制,把异步消息的优先级高于同步消息,ViewRootImpl.scheduleTraversals方法就使用了同步屏障,保证UI绘制优先执行(performTraversals())。
1
2
3
4
5
6
7
8
9
10
11
12
13
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}

mTraversalRunnable是一个Runnable对象,run方法中会调用performTraversals()执行UI绘制。

  • Looper.loop()为什么不会阻塞主线程?
    loop方法会调用MessageQueue中next方法,next()调用本地方法nativePollOnce,没有新消息时会阻塞到nativePollOnce方法,nativePollOnce方法内部是基于Linux epoll机制实现阻塞,此时主线程会进入休眠状态,不会消耗cpu资源(pip管道当有数据写入时再唤醒主线程工作)。
    引起ANR的原因是由于执行事件耗时太长,不能及时完成,而loop方法本身只是不停的循环读取消息,当有消息时loop是不会阻塞的,只有loop发送的事件耗时太长才会导致ANR。Activity的onCreate onResume 等生命周期回调方法操作时间太长才会导致卡死主线程掉帧甚至发生ANR(Activity一般超过5s就会发生ANR)。
  • Thread、Hanlder、Looper和MessageQueue的数量级关系?
    一个Thread可以有多个Handler,只有有一个Looper和MessageQueue,多个Handler创建的Message都添加到同一个MessageQueue中,Looper从MessageQueue中拿到Message通过Hadnler对象target分发到对应Handler处理回调。
    Thread(1)==>Looper(1)==>MessageQueue(1)==>Handler(N)

  • 引起内存泄漏的原因以及解决方案?
    原因:由于java的特性,内部类会持有外部类的引用,所以Handler会持有Activity,Message中target对象又是Handler的引用,所以Message就持有了Activity,Activity调用销毁后如果当前HandlerMessage还在MessageQueue中,导致Activity不能被及时回收。
    解决方案:
    将Handler定义为静态内部类,持有Activity的弱引用并在Activity销毁时调用removeCallBacksAndMessages(null)移除所有消息。
  • Handler发送一个延时消息是怎么更新MessageQueue?
    如果此时MessageQueue中只有这个延时消息,消息不会被马上发送,而是计算唤醒时间让Looper阻塞,到唤醒时间时再唤醒Looper执行消息发送。如果MessageQueue中还有Message,延时消息被插入到时间排序的对应位置,MessageQueue中对头的when值最小,越往队尾值越大。