介绍
Handler主要用于异步消息的处理。比如在安卓中我们可以通过Handler将消息从子线程发送到主线程中来更新UI。如下便是handler在子线程中延迟2s发送一个消息,然后再发送一个没有延迟的消息,接收这些消息的handleMessage方法运行在主线程中,在收到消息后就可以更新界面了,界面上就会依次显示"这是message2哦","这是message1哦"。
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String text = (String) msg.obj;
tvTest.setText(text);
}
};
new Thread(new Runnable() {
@Override
public void run() {
Message message1 = Message.obtain();
message1.obj = "这是message1哦";
Message message2 = Message.obtain();
message2.obj = "这是message2哦";
handler.sendMessageDelayed(message1,2000);
handler.sendMessage(message2);
}
}).start();
源码分析
Handler的使用简单来说,可以分为实例化Handler对象,Handler发送消息以及handleMessage接收消息的过程,这里从Handler的实例化开始分析学习。
Handler的实例化
Handler的构造方法
public Handler() {
this(null, false);
}
转而调用两个参数的构造
public Handler(Callback callback, boolean async) {
//...
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
这里进行了一些赋值操作。主要是获取当前线程的Looper对象,然后初始化了MessageQueue对象。
Handler发送消息
调用sendMessageDelayed
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
如果调用sendMessage方法,也会转而调用这个方法,只是将延迟时间置为0。调用sendMessageAtTime
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);
}
对局部变量queue进行了赋值,判断为空的话抛出异常,调用enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这里指定msg的target为当前handler对象,将msg消息传入queue消息队列的enqueueMessage方法
boolean enqueueMessage(Message msg, long when) {
//省略空判断,抛异常代码
synchronized (this) {
//省略状态判断,抛异常代码
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
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 {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
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;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
该方法负责处理传入的消息。消息队列是链表的结构,这里根据传入msg的when延迟时间按从小到大对消息队列进行了排序。
发送消息的过程,是对msg消息对象进行了入队并且按照延迟时间进行排序的操作,就形成了一个链表。
消息的循环
消息的循环是通过Looper消息轮询器调用Looper.loop()进行的,那就看一下loop方法
public static void loop() {
final Looper me = myLooper();
//省略部分判空,抛异常代码
final MessageQueue queue = me.mQueue;
//...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//省略部分log打印代码
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
}
//省略部分log打印代码
msg.recycleUnchecked();
}
}
首先获取到looper和queue对象,然后进入一个for循环,在该循环中不断遍历取出消息队列中的消息对象,并调用dispatchMessage进行消息的分发。这个target对象在enqueueMessage中赋值为当前handler,所以就是调用handler的dispatchMessage方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
msg.callback是一个Runnable对象,如果初始化Message时指定了,则会调用它的run方法执行该Runnable。mCallback是一个CallBack对象,如果在初始化Handler时指定了,则会调用它的handleMessage方法。否则会调用handleMessage
public void handleMessage(Message msg) {
}
这个handleMessage为空实现,最后由我们自己复写来实现具体处理逻辑。而这个方法执行在创建Handler时使用的Looper中执行,这样就代码代码逻辑切换到指定线程中执行了。
消息的回收和复用
在Looper.loop方法最后,执行了消息的回收
msg.recycleUnchecked();
调用recycleUnchecked
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
将消息的各个属性置为空,然后将该消息存入链表中以便复用,其中MAX_POOL_SIZE值为50。
当我们调用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();
}
获取消息时首会判断sPool当前消息如果不为空的话,就会从链表中取消息返回。否则则会创建一个新的Message对象返回。这样就完成了,Handler发送消息,Looper轮询消息,处理消息,以及回收复用消息的一系列操作。