Android的Handler
上一篇讲了android的handler通信机制,也仅仅是说了他们之间是如何工作的,但是究竟Handler, Looper, MessageQueue是如何运作的呢?今天就来分析下Handler。
构造函数
Handler是Framework中一个类,他的具体路径为:android.os.Handler
。看他的类定义可以发现,他就是一个普通的public class
,使用Handler也需要使用它的具体实例对象。既然是实例对象,我们就先看下它的构造函数吧。
#1
public Handler() {
this(null, false);
}
#2
public Handler(Callback callback) {
this(callback, false);
}
#3
public Handler(Looper looper) {
this(looper, null, false);
}
#4
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
#5
public Handler(boolean async) {
this(null, async);
}
#6
public Handler(Callback callback, boolean async) {
......
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;
}
#7
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
以上就是Handler的所有的构造函数,总共有7中重载形式,我们平时用的最多的应该是第1种,可以发现最终构造函数的构造结果就是初始化了4个实例变量:mLooper
, mQueue
, mCallback
, mAsynchronous
。
mLooper
很好理解,就是创建Handler所在线程的Looper
;mQueue
就是和Looper
关联的消息队列,mCallBack
平时用的比较少,可以看下使用到mCallBack
的位置:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
public interface Callback {
public boolean handleMessage(Message msg);
}
可以发现,mCallBack
就是一个接口,接口实现了handleMessage(Message msg)
方法,所以我们可以看到如果你在定义handler是传递了mCallback,消息处理就会走自己的逻辑,否则就会走handler自己的handleMessage函数。
最后就剩下一个mAsynchronous
变量了,这个变量表示handler发送的消息会不会被同步人所阻塞,如果设置为true,发送消息如果遇到同步事件,则消息会一直延迟到同步事件结束后才会发送和处理。
消息发送
使用handler的原因就是要进行消息通信,消息发送就是非常重要的内容。handler中发送消息的理解其实很简单,都是函数的重载,具体的理解可以看handler中sendXXX
函数,所有的sendXXX
函数最终调用都会到:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以发现,最终所有的消息都会调用enqueueMessage()
函数进入消息队列然后开始循环。
消息处理
在Android通信机制–Handler中已经说了handler的消息处理,其实就是调用handler的dispatchMessage
。