首先需要明白,handler发消息是为了做异步操作.异步大家都很清楚.一个比较常用的例子就是.一个辅助线程要更新UI线程的画面,直接用View操作是不行的.这就需要异步更新.给UI线程发消息,让他更新.
那Handler是如何做到异步发消息更新的呢?需要解决以下几个问题.
系统如何知道我这个handler是给哪个线程发消息.
系统是如何做到异步的呢?
看代码吧.在UI线程启动后,会
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
这样就创建了个Looper, 并且在构造函数中创建消息队列,并且集注当前线程.
private Looper() {
mQueue = new MessageQueue(); //转载者补充:消息队列是由Looper创建的
mRun = true;
mThread = Thread.currentThread();
}
当我们在创建handler对象时候.以下代码位于Handler的构造函数中。
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
在我们handler里会有了这个looper引用。以及得到该looper的消息队列.
MessageQueue
消息队列MessageQueue是一个以执行时间为序的优先级队列:
o 普通消息的执行为当前时间,先发送的在前面,后发送在后面,这是典型的FIFO。
o 最高优先级的消息执行时间为0,所以直接插在队列的最前面,通常会立即执行。
o 而在将来执行的Message相当于timer,执行时间为当前时间+delay的时间。
MessageQueue的函数boolean enqueueMessage(Message msg, long when)用来向队列中插入消息。
那如何证明这句话呢?
看enqueueMessage的具体实现过程.
msg.when = when;
//Log.d("MessageQueue", "Enqueing: " + msg);
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
this.notify();
} else {
Message prev = null;
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
msg.next = prev.next;
prev.next = msg;
this.notify();
这就看出来了,根据when把消息插到消息队列里,根据时间顺序,时间值小的放前面,大的放后面.排序了.
转载者补充:用链表实现了消息队列,如果当前消息的when为0或者小于消息队列第一个消息的when,那么就把该message作为链表(消息队列)的第一个元素,将mMessage指向它,即mMessage指向消息队列的第一个元素。否则,将遍历这个消息队列链表,直到找到比当前message的when大的消息,并在之前插入。
Handler
Handler 对消息队列的enqueueMessage做了包装,这其实并不重要,因为完全可以直接调用enqueueMessage来实现。重要的Handler在包装enqueueMessage的同时,把Message的target设成了自己,即为Message指定执行的行为:
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this;
sent = queue.enqueueMessage(msg, uptimeMillis);
}
这样一来,当前Message被处理的时候就会调用Handler的dispatchMessage,而这个函数就会调用你要实现的虚函数handleMessage了。经过消息队列代码转了一圈,还是调用了你自己的实现函数,但是同步操作变成了异步操作。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
当我们send消息时候,过程就很明朗了.
所有的发送消息的动作代码都会跑这步.把消息按系统时间送到消息队列里.那发送进去了.什么时候取出来呢?
Message放在消息队列里了,谁来一个一个的取出来处理呢?这时轮到Looper上场了,它的函数loop会一直循环处理队列中的消息,直到遇上一个没有target的Message:
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
msg.target.dispatchMessage(msg);
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
msg.recycle();
}
}
}
由此可见:一个Looper总是和一个MessageQueue关联起来的。
Thread
loop只是一个函数,它也需要别人来执行它。由于它一执行就会阻塞在那里,所以一定需要一个线程来调用:
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare();
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop();
* }
* }
一个Looper也总是和一个Thread关联起来的,不过不一定要创建新线程,可以是主线程的。Handler和Thread不是一一对应的,理论上,在一个LooperThread中,可以有任何多个Handler,每个消息都可以指定不同的Handler,因为每个消息都可以有不同的行为。
在创建Handler时并不会创建Thread,它只是取当前线程的Looper的MessageQueue:
public Handler() {
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 = null;
}
通过myLooper取出当前线程的Looper:
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
这个Looper是在Looper.prepare里创建的:
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
这个过程就很清楚了,UI线程启动后,会不断的从消息队列取消息,当没有消息时候,会
while (true) {
Message msg = queue.next(); // might block
在这阻塞,直到有消息近来,然后通过 msg.target.dispatchMessage(msg);
来调用我们的handler注册的HandleMessage来处理消息.
962

被折叠的 条评论
为什么被折叠?



