上周其实已经写好了关于handler messager looper机制的文章,而且已经保存了。两天后写http://blog.csdn.net/u014529755/article/details/48197923 这篇文章的时候,竟然诡异地将那篇给删了。OMG。切换到markdown模式的时候上次写的东西竟然还在,而且直接可编辑,不知道大家有没有遇到过这样的问题。
言归正传,让我们来一起讨论handler messager looper机制。我先用一句话来概括他们的关系:在线程通信中,用handler来处理由looper管理的消息队列里面的message。下面是他们的具体分析:
1.Looper对象的创建
对于每个线程,它都有且仅有唯一一个Looper对象,你可以将它看成消息管家。下面是Looper类的几个属性
public final class Looper {
private static final String TAG = "Looper";
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
final MessageQueue mQueue;
final Thread mThread;
从中我们可以看到
- Looper类是final 类型的,不可被继承
- Looper类中的mQueue就是我们讨论的消息队列,mTheard就是Looper对象对应的线程
对于主线程而言,当创建主线程(也就是UI线程)之初,同时系统也创建并运行了Looper对象。对于非主线程,Looper对象的创建由Looper.prepare()静态方法来实现,运行为looper.looper()方法。下面我们来具体看看这两个方法
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对象。否则抛出Runtime异常,一个线程只许有一个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;
// 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();
}
}
looper()方法的作用在于一直循环检测消息队列中的消息,如果有则通过hander来处理消息,至于如何将looper和handler联系起来,我们在后面讨论。这里我们着重来看两个方法
- final Looper me = myLooper();//获取Looper对象
- final MessageQueue queue = me.mQueue;//获取Looper对象中的消息队列
- Message msg = queue.next(); // 获取下一条消息。
- msg.target.dispatchMessage(msg);//分发消息
上面的msg.target其实就是handler对象,handler通过diapatchMessage()方法来执行回调函数handleMessage(),这个方法熟悉了吧就是我们定义handler时重写的方法。
2.Handler及其处理消息的方式
通过上面我们已经知道了,通过looper()一直对消息队列进行管理,一旦有消息在队列中,就取出来交给handler来处理。那么这些消息从哪里来,怎样添加到消息队列中去的呢。这里我们有必要将handler类给大家介绍一下。
//handler中的一些属性
final MessageQueue mQueue;
final Looper mLooper;
final Callback mCallback;
final boolean mAsynchronous;
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以及对象中的消息队列是handler中的属性,这样我们就通过handler来对消息队列进行操作。那么我们通常使用的sendMessage()方法如下:
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这儿我们再次看到了msg.target。前面我们在looper()方法中的有一句
msg.target.dispatchMessage(msg)来处理消息。msg.target = this;其实就是设置target为当前的handler,这样我们就可以将三者的关系理顺了
Thread中的Looper对象创建之后执行looper()开始循环:looper对象中有MessageQueue,如果队列中有Message,则取出来执行msg.target.dispatchMessage(msg)方法。dispatchMessage(msg)方法会将消息分发给Handler对象中的handlerMessage()方法来处理Message。这样消息的处理就完成了。同时Hander的SendMessage()方法将消息发送添加到消息队列中,等待looper循环处理消息。
下面这个是handler中消息分发的代码:
/**
* Handle system messages here.g
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handleMessage()就是我们在定义Handler时复写的方法,用于处理消息。
大概到这儿,这三者的关系差不多就整理清楚了。如有问题,还望指出