Handler大家最熟悉不过,每次重新回顾Handler都有不同的感觉,学到新的东西。现分享一些自己对Handler的理解。
Handler发送消息
- 首先Handler通过sendMessage方法将Message发送到MessageQueue消息列对中。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
- 点击查看源码
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);
}
大体意思是获得消息队列,开始如入队列。这里mQueue为Handler的成员变量,Handler里并没有说明这个对象从哪里来的。先继续往下分析。
- 入消息队列
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target = this;将Handler类这个对象赋值给Message的target变量。这就说明在入队列的时候Message对应的Handler都是绑定好的。可以有多个Handler。之后Looper循环取消息的时候会用到。
- Handler分析到这儿,下面进入MessageQueue
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
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;
}
Message prev;
for (;;) {
prev = p;
p = p.next;
一个死循环,底层是链表结构,先进先出的底层原理。消息列队会按顺序执行。值得重点的是这行代码 if (needWake) {
nativeWake(mPtr);
}
nativeWake指的是唤醒Looper消息泵,开始取消息。
- 进入Looper分析源码
Looper中是消息泵 内部启动一个死循环泵消息。没有消息会休眠,有消息放入MessageQueue中的时候会唤醒。俩个重要的方法,prepare(), loop();
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));
}
prepare方法中,sThreadLocal为ThreadLocal的对象,
static final ThreadLocal< Looper > sThreadLocal = new ThreadLocal< Looper >();类似一个集合,底层hashmap。
在thread线程开始前调用get方法,Looper只能实例化一次
如果不为空则抛出”Only one Looper may be created per thread”异常。然后set方法保存looper
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
set方法中通过获取当前线程保存到ThreadLocalMap当中
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
Loop方法中首先final Looper me = myLooper();获取当前的looper,mylooper通过ThreadLocal的get方法得到。
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
get方法同理也是通过当前线程及map获取looper
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
if (me == null) {
throw new RuntimeException(“No Looper; Looper.prepare() wasn’t called on this thread.”);
}
注意到如果在子线程Handler没有调用looper.prepare(),就会抛出这个异常。
之后MessageQueue中顺序取消息,重点是下面代码
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
looper中msg.target是绑定的Handler , handler分发消息,处理消息。这样一个流程完成
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
而CallBack接口中的**handleMessage**则是回调处理消息的方法。
public interface Callback {
public boolean handleMessage(Message msg);
}
最后我们解决一下前面提到的Handler中的mQueue来源
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
mQueue是在looper构造器创建初始化的,
以Handler的默认构造器为例,构造器里 mLooper = Looper.myLooper();获取looper, mQueue = mLooper.mQueue;获取了消息队列。
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;
}
小结
整个Handler流程从发送Message到handleMessage,经历了入队,Loop消息出队列,再用之前绑定的Handler分发消息。像是一个走了一个圈又回归到最初,这样的思想很好的解决了异步处理耗时,并及时通知UI更新,避免了anr。并且我们知道Handler是哪个线程的由Looper决定,需要注意的是Handler的默认构造是获得的主线程的looper。所以不需要looper.prepare(),系统帮我们做好了。就这些吧,文章短小,但还是比较精简的能快速理解原理。水平有限,难免有不足,望大家能给予斧正。