这几天由于比较空,仔细读了下Handler,Looper,Message和MessageQueue的源代码,再结合一些现有的资料(比如任玉刚的Android开发艺术探索),深入的理解了一下Android是如何进行线程切换,异步加载的。
在介绍之前,首先要对几个主要类进行理解。
Looper类
Looper类比较简单,主要只有2个操作
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的构造函数初始化Looper对象的,然后把looper对象赋值给ThreadLocal(这个类在下面会进行介绍)
和
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,只要取到Message就调用msg.target.dispatchMessage(msg);
Handler类
有几个构造函数
//无参数的构造函数,主要调用Handler(Callback callback, boolean async)这个函数,在这个2个参数的构造函数里详细讲下
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
//调用了public Handler(Looper looper, Callback callback, boolean async)
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);
}
//这里的Callback是Handler里的一个内部接口,如果外部类继承了这个接口,可以把这个类作为Handler的代理类,代替Handler去执行HandlerMessage的操作
然后 boolean async是用于判断message每次send或者post的时候是否需要同步
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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
就用注释主要讲解下我们常用的几个构造函数
我们一般在程序里在主线程都使用 new Handler()的方式去获得一个Handler的实例,因为Looper.myLooper()得到的就是mainLooper。在子线程如果这么调就会报错
throw new RuntimeException(“No Looper; Looper.prepare() wasn’t called on this thread.”);
原来就是主线程会在线程启动时调用prepareMainLooper()方法,去new 一个Looper的实例,但是子线程需要我们手动去实现一个Looper的实例
,需要调new Handler(Looper.getMainLooper())方法
然后Handler里有几个常用的方法
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
这2个方法的本质是一样的都是调用了sendMessageDelayed方法
post(Runnable r)方法多执行了一步,就是把Runnable包装成一个Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
这里会生成一个Message,然后把Runnable作为一个成员变量的形式赋值给message,至于为什么这么做,会在下面Handler如何处理Message中讲到
然后我们再跟着代码走,
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);
}
这里看到sendMessageDelayed方法只是简单的对delayMillis进行处理,如果小于0,就赋予0值。而sendMessageAtTime也只是对MessageQueue进行了非空判断。最后把只是简单的把message塞进了MessageQueue当中
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//这里有一个我认为比较聪明的做法,把Handler做为一个target给Message,等Message取出来的时候,就能很轻松的获得Handler的对象
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这样整个发送消息的过程就结束了
post/sendMessage->sendMessageDelayed->sendMessageAtTime->
enqueueMessage 主要流程就是把MessageQueue当中
然后再讲下取的过程
Looper在取到Message后,会调用msg.target.dispatchMessage(msg)(就是上面说到Looper.loop()里干的事);
然后会调用
/**
* 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);
}
}
//这里的msg.callback就是我们之前把Runbale赋值给Message时获得的。
//如果你给msg设置了callback handlerMessage方法就会不执行, 如果遇到这个问题的同学就会明白为什么了
//然后会去判断代理是否为空,如果不为空就让代理去执行handlerMessage方法。
//只有上述2个条件都为空才会执行我们熟悉的HandlerMessage方法
这样我们就能用Handler去执行我们之前在子线程希望UI线程干的事情了,但是为什么这样就切换到UI线程了,这个就跟ThreadLocal有关了和Looper有关了,会在下一章讲明白
Message和MessageQueue在这就不多说,因为代码非常简单,Message就是一个实体类和我们在平时定义的业务实体类一样。
MessageQueue就是一个单向链表,插入和删除消耗比较少。