本文用AndroidStudio追寻源码的方式来分析Handler消息机制
1、应用程序的入口是ActivityThread类中的main方法,当打开应用程序时,会首先调用ActivityThread类中的main()方法;而main()方法中主要调用了Looper.prepareMainLooper()和Looper.loop()两个方法
public static final void main(String[] args) {
//初始化looper Looper.prepareMainLooper();
//将轮询器轮询起来
Looper.loop();
}
2、先看Looper类中的prepareMainLooper()方法,调用了prepare(false)方法
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
//保证主线程Looper唯一
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Looper中的prepare()方法,创建了Looper对象
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建Looper对象
sThreadLocal.set(new Looper(quitAllowed));
}
Looper的构造方法,创建MessageQueue消息队列
private Looper(boolean quitAllowed) {
//创建MessageQueue消息队列
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
3、然后继续调用ActivityThread类中的Looper.loop()方法
public static void loop() {
//获取Looper对象和MessageQueue消息队列
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;
//开始无限轮询 ,注意这里是死循环在Android2.3的源码时用的while(true)循环
for (;;) {
//只要消息队列中有消息,不断的从消息队列中取消息
Message Message = queue.next();
might block if (Message == null) {
return;
}
//处理消息
Message.target.dispatchMessage(Message);
//回收消息
Message.recycleUnchecked();
}
}
4、发送消息时创建Handler对象的过程,Handler重载的构造很多,但最终调用的是两个,或者三个参数的构造,最终目的就是将Looper对象和MessageQueue对象的引用保存到Handler的成员变量中
public Handler() {this(null, false);}
public Handler(Callback callback) {this(callback, false);}
public Handler(Looper looper) { this(looper, null, false);}
public Handler(Looper looper, Callback callback){this(looper,callback,false);}
public Handler(boolean async) {this(null, async);}
public Handler(Callback callback, boolean async) {
//获取当前线程的Looper对象,并保存到Handler的成员变量中
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException("Can't create handler inside thread that has not called Looper.prepare()");
}
//将Looper中的MessageQueue保存到Handler的成员变量中
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public Handler(Looper looper, Callback callback, boolean async) {
//获取当前线程的Looper对象,并保存到Handler的成员变量中
mLooper = looper;
//将Looper中的MessageQueue保存到Handler的成员变量中
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
5、然后我们要先明白,消息是从Message的回收队列中取出来的,那我们去看一下Message回收队列的实现原理,回收消息是调用了Message类的recycle()方法
public void recycle() {
recycleUnchecked();
}
/*package*/ Message next;
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
void recycleUnchecked() {
synchronized (sPoolSync) {
//判断回收队列是否比队列的最大值大
if (sPoolSize < MAX_POOL_SIZE) {
//此处代码是消息回收队列的核心代码,我用图来分析原理
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
6、接下来,我们看一下如何从消息回收队列取出一条消息,一般我们用Message.obtain()方法来获取一条空消息
public static Message obtain() {
synchronized (sPoolSync) {
//判断消息池中是否有消息
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0;
// clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
7、现在空消息已经获取到,继续看Handler发送消息的过程,我们发送消息有三种形式:最常见的是调用handler.sendMessage()发送一条消息,最终会调用handler.sendMessageAtTime(Message Message, long uptimeMillis)方法
public final boolean sendMessage(Message msg){ return sendMessageDelayed(msg, 0);}
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) {
//获取Handler中的消息队列
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);
}
继续看enqueueMessage(queue, msg, uptimeMillis)方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//将当前handler对象的引用赋值给Message中的target变量
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//调用c库中的方法将消息添加到消息队列
return queue.enqueueMessage(msg, uptimeMillis);
}
8、第二种常见的发送消息的方法是handler.post(Runnable r),最终也是调用的sendMessageAtTime(Message msg, long uptimeMillis)方法,添加一条消息到消息队列
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis){
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
接下来看Runnable 对象在哪被调用,当你用post的方式发送一条消息时,会调用getPostMessage()方法来获取该消息,并将该消息的runnable的应用赋值给Message的callback变量
/*package*/ Runnable callback;//Message类中的callback成员变量
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
//将runnable接口的引用赋值给Message的callback变量
m.callback = r;
return m;
}
9、第三种发送消息的方法是在创建Handler对象的时候传一个Callback引用进去,Handler部分的代码看第4条的代码,Callback原来是个接口,而且有一个抽象方法需要重写,这和空参的new Handler(),原理是一样的
public interface Callback {
public boolean handleMessage(Message msg);
}
10、消息添加到消息队列中后,由Looper.loope();一直在执行,会不断从消息队列中取出消息,并调用Message.target.dispatchMessage()方法处理消息
public void dispatchMessage(Message msg) {
//判断Message中的callback变量是否为空
if (msg.callback != null) {
handleCallback(msg);
} else {
//判断Handler中的mCallback变量是否为空
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//处理sendMessage();方法发送的消息
handleMessage(msg);
}
}
首先,Handler处理消息的时候会优先判断Message中的callback是否为null,不为空的话调用handleCallback(Message),执行我们重写的run()方法
private static void handleCallback(Message message) { message.callback.run();}
其次,Handler会判断自己的成员变量mCallback是否为null,不为空的话执行mCallback.handleMessage(Message),也就是创建Handler对象时传进去的接口的抽象方法
public interface Callback {
public boolean handleMessage(Message msg);
}
最后调用我们创建空参Handler对象时所重写的handleMessage(Message msg)方法
//该方法为空实现,是我们在创建Handler对象的时候重写的handleMessage()方法,根据msg.what进行消息处理
public void handleMessage(Message msg) {}
补充:
1、Message回收队列的实现原理
Message回收队列,以链表的形式不断的将回收到的Message添加到链表的头部,此时消息的回收已经完成了
2、从Message回收队列中获取一条空消息进行复用
我还是以画图的形式来分析取消息的过程
3、发送一条消息到MessageQueue的过程分析,看MessageQueue中的enqueueMessage()方法中的代码
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 {
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;
}
到现在,Handler消息的整体流程就走完了,欢迎大家批评指正!
推荐:
Message在MessageQueue中的入列和出列流程
http://www.jianshu.com/p/a8708d315039