Handler相关知识梳理
1、为什么要使用Handler?
因为Android系统只能在主线更新UI,而我们的数据操作经常是由子线程来完成的。为什么子线程不能更新UI?因为如果多线程操作UI会导致UI处于不可预知的状态;那可不可以用加锁的方式来解决这个问题呢?加锁会让访问UI的逻辑变得很复杂,而且会降低访问效率。
2、Handler消息机制原理
在程序中,我们一般的做法是调用Handler.SendMessage等方法来发送消息,最终会调用Handler.SendMessageAtTime方法将消息插入到消息队列MessageQueue中
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;//此处的target即为Handler
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在MessageQueue.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 {
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;
}
Looper是消息机制中非常重要的一个东西,主线程会调用Looper.loop方法一直轮询,发现有消息就将消息转发给Handler
那么主线程的Looper是怎么创建的呢?
在应用程序启动的过程中,会创建一个主线程,ActivityThread,看它的main方法(应用程序的真正入口)
public static void More ...main(String[] args) { //只贴了相关的代码
Looper.prepareMainLooper();//为主线程创建了Looper
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler =thread.getHandler();//主线程的Handler
}
Looper.loop();//进入消息循环
}
重点来看Looper.loop()方法:
public static void loop() {
final Looper me = myLooper();//调用了sThreadLocal.get()来获取当前线程的looper,ThreadLocal以UI线程为KEY,以Looper为值这样就把一个线程和一个looper关联起来了
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
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;
}
// 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);//此处即通过Message中保存的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);
}
}
public void handleMessage(Message msg) {
}
可以看到,最终调用的handleMessage方法是一个空方法,也就是我们在new一个handler时重写的方法
我们再来看看Looper的构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到,在Looper的构造方法中,new了一个消息队列
而在我们的Handler的构造方法中:
public Handler(Callback callback, boolean async) {
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;
}
所以,通过Handler发送的消息,插入的消息队列是Looper new出来的
3、图解