我们在面试的时候经常会被问到Handler机制,我们一般回答的很简单,比如答到用来发送及处理消息,处理子线程向主线程发出的消息。对于面试官而言,这或许并不是他们想要的答案。今天,我打算从源码的角度去追溯一下,Handler究竟是怎么样的一个执行机制。
首先,我们知道Handler里面发送消息包含了下面的几种方式
例如:
首先,我们进入到Handler.jave类,查看sendMessage(Message msg)方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
上面的代码依次又调用了sendMessageDelayed(msg, 0);
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
做了一个判断,由于传进来的是0,我们可以忽略掉上面的判断,直接看下面的sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
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);
}
上面我们看到的是拿了一个MessageQueue对象,假设我们的这个对象不为空,跳过判断,直接我们在接着看下面的enqueueMessage(queue, msg, uptimeMillis);
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
queue.enqueueMessage(msg, uptimeMillis);主要做的就是将msg消息装在MessageQueue这个对象中
下面我们看一下,怎么把Message拿出来?
Handler.java类的构造方法
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;
}
不错, mQueue = mLooper.mQueue; 一看,是Looper里面来的。
下面我们就要分析一下,Looper是个啥?跟MessageQueue有什么关系?
mLooper = Looper.myLooper();
static final ThreadLocal sThreadLocal = new ThreadLocal();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
Looper的实例对象,在每一个线程中独立存在。也就是Looper拿到Thread的实例对象引用
ThreadLocal是什么呢?
ThreadLocal也是为了解决共享数据(对象)的问题,同步锁的思路是线程不能同时访问一片内存区域,而ThreadLocal的思路是,干脆给每个线程Copy一份一抹一样的对象,各自玩自己的,互相不影响。
这样,就拿到mLooper,然后mLooper调用loop()方法,获取到MessageQueue,拿出Message
Looper.java
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.isTagEnabled(traceTag)) {
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();
}
}
上面我们还遗留了一个问题,MessageQueue是怎么来的?
在看代码的时候,发现 MessageQueue queue = mQueue;,那mQueue是怎么赋值的?
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
大致我们清楚了,我们在handler发送Meesage,有这个几个过程?
1、当我们调用snedMessage(msg)的时候,Handler类里面会启用Looper类里面的Looper方法,创建MessageQueue,并获取当前线程的引用。然后将msg存进去
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
2、当我们去拿数据的时候,由于我们的Looper.loop()方法在回调handleMessage(Message msg)方法后执行。它会不停的拿到当前的MessageQueue,从而遍历消息。