为分析agera做准备!带你了解Android的handler机制

Google最近在Github上开源了一个响应式框架——agera,我个人对这样的技术是比较感兴趣的,在这之前也学习过RxJava,所以想着给大家带来有关于这两者分析的博文。

在我翻阅agera的源码的时候,发现里面整个event事件驱动都是靠Android的handler机制,并且使用了ThreadLocal进行线程隔离,所以在分析agera之前,我们要先了解handler机制,为之后打下基础。

Handler机制

对于handler大家一定不会陌生,在Android中,hanlder的作用一般就是用来通信,传递信息,相信大家如果写过异步通信的代码的话,除非使用第三方框架或者AsyncTask,一般大家都会使用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
public class MainActivity extends AppCompatActivity {

private TextView tv;

private Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
tv.setText("got msg!!");
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.show);
}

public void post(View view){
handler.sendEmptyMessage(0);
}
}

当你点击按钮之后,handler通过sendEmptyMessage()这个方法将消息传递了出去,并且在对应的handleMessage()方法中处理。这个handler是在主线城中创建的,但是大家如果使用相同的代码在子线程中创建一个handler的话,会得到如下错误:

handler_error

错误的原因是不能在没有调用Looper.loop()的前提下在thread中创建handler,那这个Looper是什么呢,下面让我带大家进行分析。

Looper

1
2
3
4
5
6
7
8
9
10
11
12
13
public final class Looper {
/*
* API Implementation Note:
*
* This class contains the code required to set up and manage an event loop
* based on MessageQueue. APIs that affect the state of the queue should be
* defined on MessageQueue or Handler rather than on Looper itself. For example,
* idle handlers and sync barriers are defined on the queue whereas preparing the
* thread, looping, and quitting are defined on the looper.
*/


......
}

通过注释可以看到,它是用来进行消息循环的类。在我们调用前面提到的Looper.loop()方法之前,要先调用它的prepare()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** 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));
}

通过注释可以清楚的了解这个方法的作用是创建一个Looper并且让handler去持有,在调用looper()之前必须保证已经调用了prepare()。

1
2
3
4
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));

下面这段函数牵扯到了ThreadLocal,这个我之后会讲,这里大家需要了解的就是这段函数的作用是用ThreadLocal去判断是否有Looper实例,如果有则抛出异常,没有就新建一个并且存放到ThreadLocal中。首先ThreadLacol是线程隔离的,这样做就保证了一个线程中有且仅有一个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
/**
* 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();
}
}

通过注释可以看出这个方法的作用是开启一个message queue的循环。

在loop()方法中首先通过myLooper()方法去获取当前线程中的Looper实例。

1
2
3
4
5
6
7
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/

public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

然后获取到Looper中的MessageQueue。

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

这段代码的意思是开启一个死循环,在其中通过queue.next()去获取MessageQueue中消息,这里是会阻塞的。

1
Message msg = queue.next(); // might block

一旦获取到了消息,就调用Message的target实例去分发消息。

1
msg.target.dispatchMessage(msg);

然后将Message进行重用。

1
msg.recycleUnchecked();

这里有一个小细节,如果大家想得到一个Mesaage的话,最好不要通过new的方式去新建,而是通过下面这种方式。

1
handler.obtainMessage();

或者

1
Message.obtain();

至此,Looper的分析就完了,很简单,就做了两件事。

第一,通过Looper.prepare()去新建一个Looper实例。

第二,通过Looper.loop()去开启消息循环。

但是大家看了上面的代码肯定有一个疑问,在通过MessageQueue得到传递过来的Message之后调用的

1
msg.target.dispatchMessage(msg);

这个方法,target是什么呢?下面就让我们继续分析Message类。

Message

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
*
* Defines a message containing a description and arbitrary data object that can be
* sent to a {@link Handler}. This object contains two extra int fields and an
* extra object field that allow you to not do allocations in many cases.
*
* <p class="note">While the constructor of Message is public, the best way to get
* one of these is to call {@link #obtain Message.obtain()} or one of the
* {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
* them from a pool of recycled objects.</p>
*/

public final class Message implements Parcelable {
.......
}

Message其实就是一个消息的实体类,实现了Parcelable用于传递。

这个类大家不会陌生,里面有几个成员变量

1
2
3
4
5
6
7
public int what;

public int arg1;

public int arg2;

public Object obj;

大家经常用到,这里我就不做介绍了。还是让我们看看target是什么。

1
/*package*/ Handler target;

target是一个Handler。那么这个Handler又是怎么被赋值的呢?

是在Handler中被赋值的,下面让我们来看Handler的代码。

Handler

1
2
3
4
5
6
7
private Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
tv.setText("got msg!!");
}
};

首先这是我们初始化的代码,让我们看看Handler的构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public Handler() {
this(null, 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;
}

直接通过Looper.myLooper拿到当前线程的Looper实例。

1
2
3
4
5
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}

这里就可以联系上面的那个错误了,为什么我们在子线程中不调用Looper.prepare()直接使用handler会报错呢?就是因为这里,如果通过Looper.myLooper()去ThreadLocal中取不到对应线程的Looper就直接报错了。那为什么我们在主线城中不用显示的调用Looper.prepare()和Looper.loop()呢?那是因为Android Framework层已经帮大家做了这样的事。这是合理的,因为其实Android Framework层中很多地方都要用到handler通信,所以它干脆直接帮你做了初始化的工作。

接着把Looper的MessageQueue赋值到自己这里。

1
mQueue = mLooper.mQueue;

这里就对应了前面Looper类注释中的“This gives you a chance to create handlers that then reference this looper, before actually starting the loop.”这句话,让handler持有Looper。

接着让我们看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
public final boolean sendEmptyMessage(int what)
{

return sendEmptyMessageDelayed(what, 0);
}

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{

if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

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

所有和发送消息有关的代码最终都会走到sendMessageAtTime()这个方法中。在这个方法中获取到了当前的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);
}

看到了吗,这里将对应的msg的target赋值,也就是Handler把自己赋值给了Message。然后丢到Queue中。

然后,如果你调用过Looer.loop(),在其中MessageQueue的next()方法就会接受到对应的Message,之后的流程上面已经讨论过了。

至于Handler的post方法只是做了一层封装而已。

1
2
3
4
5
6
7
8
9
10
public final boolean post(Runnable r)
{

return sendMessageDelayed(getPostMessage(r), 0);
}

private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

最终调用的还是sendMessageAtTime()这个方法。

总结

这里要总结的一点是,Handler的onHandle()方法执行的线程是和Handler创建的线程相关的,如果你Handler在主线程中创建,就算你在子线程中send msg,最终还是会回到主线程中进行处理,反义亦然。因为你Handler中持有的MessageQueue所在的线程是在创建的时候就决定了的,所以分发的时候也是在对应的线程。

这也是为什么我们可以通过handler去做异步操作的原因。

有了这方面的基础,下篇文章就可以带大家愉快的遨游在agera的海洋中了。