一直对Handler的使用不太理解,最近看了Android 开发艺术探索中有关Android消息机制一章对此有了更深入的理解。如果其中有错误的地方,欢迎指正。
Handler的使用方法有如下三种,其实它们都是一样的,只是最终调用的回调方法不同。
(1)
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
(2)
Handler handler1 = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
(3)
handler.post(new Runnable() {
@Override
public void run() {
}
});
一、发送消息
不管是直接调用SendMessage方法还是Post一个Runnable 都会调用sendMessageDelayed方法进行发送消息。一路追踪源码就会发现其最终是调用了
消息队列的enqueueMessage 插入了一条消息,同时设置msg.target=this。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
当我们调用了Looper.loop()方法后,才会从消息队列中取消息执行,而在loop()方法中就是调用消息队列MessageQueue的next()方法取出消息,再调用Handler的dispatchMessage方法进行
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
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;
}
try {
*msg.target.dispatchMessage(msg);*
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
Handler中接受消息
/**
* 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);
}
}
第一个if语句判断的就是Runnalbe是否为空如果它不为空其实就是上边的(3)的写法。else中的第一个mCallback判断就是(2)的写法,可以看Handler的构造函数。
/**
* Constructor associates this handler with the {@link Looper} for the
* current thread and takes a callback interface in which you can handle
* messages.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*
* @param callback The callback interface in which to handle messages, or null.
*/
public Handler(Callback callback) {
this(callback, false);
}
最后的handleMessage(msg),就是(1)的写法了。
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}