说到sendMessage,开发中用的比较多,是Handler的方法,而Handler的机制,在整个Android系统中的应用非常广泛,当然,也是面试中经常问到的知识点,过一过源码,在此梳理下,
首先,一般使用Handler代码是这样的,如下:
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
}
};
//发送消息
handler.sendMessage(msg);
那么,整个机制的具体流程是怎样的呢?先看下Handler
Handler.java
public Handler() {
this(null, false);
}
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;
}
我们经常使用Handler的默认构造函数,创建Handler对象,默认构造函数内,会调用带参数的构造函数,显然 ,这里的callbcak,mCallback为null,asyn,mAsynchronous
为false,Looper的myLooper方法执行后,mLooper初始化完成,这里,可以从mLooper中获取对应的一个mQueue,也就是MessageQune
下面,就来了解下Looper的创建
1.Looper的创建:
Looper.java
private static Looper sMainLooper;
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
public static void prepare() {
prepare(true);
}
public static Looper myLooper() { return sThreadLocal.get(); }
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();
}
看完这段,大致了解到,上面Handler的构造方法中,调用Looper的myLooper()方法来获取Looper对象,myLooper()内部关系到sThreadLocal变量,通过get()方法得到Looper。同
时,我们发现在prepare(quitAllowed)的方法内部,sThreadLocal通过set设置了新的Looper实例来保存,这样,我们知道了sThreadLocal实际上是用来存储Looper对象的,并且是一
个线程只能对应一个Looper,如下:
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
注释的含义大致是,只有我们调用了prepare()方法,sThreadLocal才会返回Looper对象,否则为null。那么,我们可以这样理解,prepare()的调用,能够创建Looper对象,同时创
建了mQueue(MessageQune对象),而其内部调用prepare(quitAllowed),prepareMainLooper也调用了prepare(quitAllowed),而且,prepare()与prepareMainLooper()全部是public
static 修饰的,这说明,它们是专门供外部来调用从而获取Looper对象的。事实果真是如此吗?先来看下,省略部分无关代码,如下:
ActivityThread.java
public static void main(String[] args) {
//...
Looper.prepareMainLooper();
//...
Looper.loop();
//...
}
的确,在ActivityThread中main方法执行了prepareMainLooper(),loop()也被执行,而main方法是系统调用,同时,也就是说,系统预先帮我们创建好了Looper对象,并且开
启轮询。至于prepare(),也有用到,我们可以在子线程中使用Looper.prepare(),Looper.loop(),创建自己的Looper。记住,一定要先prepare,要知道,巧妇难成无米之炊,
体会下吧。到此,Looper的创建过程以及基本了解。
接着来看loop()是内部是如何的
2.Looper的轮询:
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;
//...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
//...
msg.target.dispatchMessage(msg);
//...
msg.recycleUnchecked();
}
}
我们注意到loop()的内部,先是获取到Looper对象,通过Looper得到对应的MessageQune,也就是mQueue。
接下来是无限的循环,不断的从mQueue消息队列中取消息,如果没有取到,消息为null,不再向下执行,继续循环取,一旦取到Message,就会通过Message的target,派发
消息,之后对已派发的Message进行回收
target实际上就是Handler,后面还会看到,在此说明下
关于消息的回收,是对消息的相关参数进行出厂设置,也就是,将参数设置为null或者0,但是,消息对象还在,没有销毁,可以重复利用,这点也可以从Message的obtain()方
法验证
好了,经过上面两个步骤,我们的Looper创建好了,也开始工作了,尽管是系统帮忙的,但是我们可以发消息了,继续看Message的发送过程
3.Handler发送消息到MessageQune:
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
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);
}
以上的过程是在Handler中完成的,消息发出后可以根据返回值,判断是否发送成功,继续看
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
//...
return queue.enqueueMessage(msg, uptimeMillis);
}
这里是上面提到的target,是this,就是当前Handler对象,也就是说,Handler发送消息时,绑定了自己,为什么绑定自己呢?这跟谁污染谁治理的原则是一样的,当然,没那
么严重,是谁发送消息,就是谁处理消息,始终唯一
接下俩,就是将Messager进行编队,入列的过程
4.MessageQueue对Message入列:
MessageQueue.java
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;
}
可以看到,内部有个无限循环,为什么要无限循环呢?因为MessageQune是很被动的,它不知道什么时候会有消息要加入,才会不断循环,只要有Message消息进来,就会将
Message进行编队,没有就跳出循环。接下来,终于等到派发Message消息,如下:Message的消息分发到Handler
msg.target.dispatchMessage(msg);
这句代码是在loop()中执行的,为了说明,最终Message是派发给当初负责发送它的Handler对象的,有点物归原主的含义,可以体会下
下面,看Handler如何回调handMessage的
5.Handler回调方法处理消息:
Handler.java
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在Handler对象创建时,mCallBack为null,callBack也为null,消息派发后,就调用handMessage方法,
文章开头,重写的handMessage方法
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
}
};
经过上面的几个过程,handMessage方法被调用,吐司最终展示在UI界面上
好啦,以上就是Handler、Looper、MessageQueue之间的关系描述,收拾下,吃饭了...