回炉再造Handler

Handler 机制

handler 的出现是为了解决子线程无法更新主线程的问题。

Handler 的使用

  • 构造函数
1
2
3
4
1: public Hanlder()
2: public Handler(Callback callback)
3: public Handler(Looper looper)
4: public Handler(Looper looper,Callback callback)

第1个和第二个构造函数的源码如下:

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());
}
}
//获取当前线程的Looper实例
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;
}

第3个和第四个同时传递了Looper对象,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
//公共的方法
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

在 第二个和第四个中还有Callback 参数,是handler的内部接口,代码如下:

1
2
3
public interface Callback {
public boolean handleMessage(Message msg);
}

handleMessage 的返回值是一个boolean值,如果为true,表示拦截msg的信息;如果为false,表示不拦截;

1
Handler 是Syncchronous 的;//Handlers are synchronous by default

创建

  • 在主线程中
1
2
3
4
5
6
7
8
9
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 101){
tv_test.setText("");
}
}
};
  • 在子线程中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MyThread extends Thread {
private Handler myHandler;
@Override
public void run() {
super.run();
//创建Looper
Looper.prepare();
myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 101){
tv_test.setText("");
}
}
};
//无限循环
Looper.loop();
}
}

同样的我们也可以利用 HandlerThread来创建handler;如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyHandlerThread extends HandlerThread {
private Handler handler;
public MyHandlerThread(String name) {
super(name);
}
@Override
public void run() {
super.run();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
}
}

Post /Send

SendMessage

根据使用场景不同,封装了不同是方法:

1
2
3
4
5
6
1: sendEmptyMessage(int what)
2: sendEmptyMessageAtTime(int what,long uptimeMillis)
3: sendEmptyMessageDelayed(int whta,long delayMills)
4: sendMessage(Message msg)
5: sendMessageAtFrontOfQueue(Message msg)
6: sendMessageAtTime(Message msg,long uptimeMillis)

通过阅读源码,我们发现上述所有的方法最终都是通过调用sendMessageAtTime()方法来达到发送消息的目的;源码如下:

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

Post Runnable

封装的方法如下:

1
2
3
4
5
1: post(Runnable r)
2: postAtFrontOfQueue(Runnable r)
3: postAtTime(Runnable r,long uptimeMills)
4: postAtTime(Runnable r,Object token,long uptimeMillis)
5: postDelayed(Runnable r,long delayMillis)

通过源码的阅读,我们发现post相关的方法源码如下:

1
2
3
4
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}

很明显,post相关的方法底层也是调用send的方法去实现的;将Runnable转化为Message的方法是 getPostMessage(r),源码如下:

1
2
3
4
5
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

两种方法的区别

  • 当发送者知道如何处理消息时,使用Handler.post() 方法,发送者直接在run()中进行处理;
  • 当接受者知道如何处理消息的话,使用Handler.sendMessage()方法,发送者将Message 对象发送出去,handler调用 handleMessage() 方法进行处理;

Handler 的好帮手

Message 、Looper 、MessageQueue

Message

Creatror
1
2
1: Message() --- 被Message.obtain()取代
2: obtain()

Message 实现了Parceable接口,Message包含:what、arg1、arg2、obj四个属性,同时可以传递Bundle,调用 setData() 方法;通过调用 setTarget() 可以指定接收的handler;

Looper

俗称消息泵,它的职责是源源不断的从消息队列中取出消息交给handler 去处理,如果队列中没有消息,那么它就会阻塞等待;

Looper 的 prepare() 方法代码如下:

1
2
3
4
5
6
7
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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));
}

这个方法中最关键的就是 sThreadLocal 对象的 get() 和 set() 方法,这个方法涉及到一个java关键字ThreadLocal ;它的作用是:保证线程中变量的唯一性;相应的 get 和 set 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

ThreadLocalMap 是一个静态内部类,其实自定义的 hashMap;将当前 ThreadLocal 对象作为 key,传入的泛型参数值作为 value,这样就达到了“在线程作用域下的变量存储”的效果。

核心方法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
public static void loop() {
//myLooper()方法调用的是sThreadLocal.get();
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//MessageQueue
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;
}
......
try {
//交给handler去处理
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
......
//回收Message 对象,
msg.recycleUnchecked();
}
}

关于Looper的代码,我们就先分析到这里;

大家可能又一个问题,那就是:loop 中的死循环难道不会阻塞主线程么?,在知乎上找到这个问题的答案:https://www.zhihu.com/question/34652589

MessageQueue

MessageQueue 是一个有单链表实现的先入先出的队列;

在Looper.loop() 中出现的next() 方法,其实就是不断的从 MessageQueue 中取出Message对象;源码如下:

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) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) { //死循环
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//msg.target = handler
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) {
// 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;
}
} 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);
}
// 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;
}
}

在看 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
54
55
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;
}

总结

在handler中调用 post () 和 send() 方法,两者最终都会调用sendMessageAtTime()方法,完成将 Message 加入到 MessageQueue 中;

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

handler 中的 enqueueMessage() 方法则调用了 MessageQueue 中的 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);
}

在Looper.loop() 方法中不断调用 MessageQueue.next() 方法取出 Message 对象,并将其返回 Handler 处理,或者调用 Message.callback() 的run方法来处理;

Handler 使用中需要注意的问题

  • 内存泄漏

    针对 Handler 引起的内存,我们可以通过以下几种方式去避免,

    • 静态内部类、弱引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static class MyHandler extends Handler {
private WeakReference<Context> reference;
public WeatherHandler (Context context){
reference = new WeakReference<Context>(context);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Activity activity = reference.get();
if (activity != null){
tv_test.setText("Hello World");
}
}
}
}
  • 全局ApplicationContext,取代原先 ActivityContext.
  • 在生命周期的最后调用handler.removeCallbacksAndMessages(null) 方法

我在面试中,被人问到过说一下 handler 机制,这个一个很平常的问题,但是也是最不好回答的问题,我们不能简简单单的说一下那些已经被说烂的东西,同时我们没有底层的源码做支撑,我们也不好说底层,那么我们的办法就是把框架层的东西说出来,这至少是我们看过的东西。

有一个同事曾经问过我,Handler 为啥会跟线程有关系?当时我没想明白,后来通过阅读源码,我知道了,简单总结一下:handler 创建的时候跟 Looper 产生了关系有一个默认的Looper,同时 Looper 的源码中有一个 ThreadLocal 变量,这个关键字保证了线程中变量的唯一性,很显然,handler 是通过 Looper 这个中间量和 Thread 产生了联系。个人的拙见不对的地方欢迎大家指正。

到此为止,Handler 的源码和运行机制我们就分析完啦。