CrayfishXu

专注Android,填坑铺路

0%

Handler源码分析

最近接到了阿里的电面,当场被虐的体无完肤,感觉到了自己的弱小,坚定了自己学习的目标,写博加深映像的决心。电面中被问到了Handler的源码,当时回答的不清不楚,只说了Handler中有Message,MessageQueue,Queue,Looper,没有说清楚个所以然,就此有了这篇博文。

源码分析–主线程中的Handler

首先我们在使用时都会在Activitynew Handler()对象,那么进入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
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
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;
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

这里主要的构造函数实现就是最后一个,在这里获取到了mLooper,mQueue,mCallback对象,但是mLooper,mQueue对象是怎么来的呢?这就涉及到了ActivityThread类了,它在Android的源码中可以找到,它是应用程序的入口,在它的main方法中就启动了一个Handler的UI线程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) {
//省略...

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();
thread.attach(false);

if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}

if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}

// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");
}

我们看到有Looper.prepareMainLooper();Looper.loop();这两个关键方法,那么进入到Looper找到prepareMainLooper方法以及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
//Looper类
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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();
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
//ThreadLocal<T>类
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}

prepareMainLooper这个方法主要去新建了Looper对象加入了sThreadLocal中,Looper实例化时初始化了mQueuemThread,这里使用了同步锁,限制了sMainLooper只有一个。接着我们看myLooper方法,它在默认构造函数里也被调用,意思就是取出当前线程的Looper对象。那么我们可以看出默认构造函数中的mLooper其实就是sMainLoopermQueue就是mLooper中的mQueue
prepareMainLooper方法看完,接着看下面的loop方法,它做了一个死循环,不断的取出MessageQueue中的消息Message进行处理,并把消息发出去,最重要的一句msg.target.dispatchMessage(msg);,就是在分发消息,以后会明白的。

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
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}

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

接着我们在主线程使用Handler发送一个消息,一般会调用post或者postDelayed方法,然后就看看这几个方法。

1
2
3
4
5
6
7
8
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}

看到这里它们调用了同一个sendMessageDelayed方法,第一个参数还调用了getPostMessage方法,接着跟进。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

这里的getPostMessage方法很重要,它实例化了一个Message对象,将线程r赋给了m.callback对象,也就是Message对象中加入了Runnable对象,接着看sendMessageDelayed方法中的代码,最终进入sendMessageAtTime方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

这里MessageQueue来自与默认构造函数中的mQueue,这里msg.target = this;赋值也就是自身Handler,那么之前说到的在loop方法中的msg.target.dispatchMessage(msg),也就是调用了Handler中的dispatchMessage方法,接着我们先跟进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) {
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;
}

这里是在做一个消息的处理,将Message对象加入到MessageQueue对链表中,那么疑问消息怎么发出去的呢?接下来会想起loop循环,就是msg.target.dispatchMessage(msg)将消息发出去的。我们就去查看Handler中的dispatchMessage方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

private static void handleCallback(Message message) {
message.callback.run();
}
public void handleMessage(Message msg) {
}

如果msg.callback不为null,就会使用前面提到的getPostMessage中的r,之后就会调用message.callback.run();将消息发出去;否则判断mCallback对象是不是null,如果不是null,就会调用默认Callback接口中的handleMessage,否则就会调用Handler默认的handleMessage方法是个空方法。

总结

整个流程大致就是这样,Message是消息,MessageQueue是消息链表,Looper是处理消息,简单的绘制了时序图,如有错误谢谢提出。
handler