Handler 可以分发 Message 对象和 Runnable 对象到主线程中, 每个 Handler 实例都会绑定到创建他的线程中(一般是位于主线程)
它有两个作用:
(1) 安排消息或 Runnable 在某个主线程中某个地方执行
(2) 安排一个动作在不同的线程中执行
在 Android 开发中 Handler 通常被用来更新 UI,原因大家应该都知道,因为主线程中不能做耗时操作(会 ANR),而子线程又不能更新 UI (线程安全问题)。
所谓 Handler 机制 简单点说就是 Handler 自己发送消息 (Message) 到消息队列 (MessageQueue),通过 Looper 轮训到消息然后再分发消息给 Handler 自己处理。
post(Runnable r)
postDelayed(Runnable r, long delayMillis)
postAtTime(Runnable r, long uptimeMillis)
postDelayed(Runnable r, long delayMillis)
sendMessage(Message msg)
sendEmptyMessage(int what)
sendEmptyMessageDelayed(int what, long delayMillis)
sendEmptyMessageAtTime(int what, long uptimeMillis)
sendMessageDelayed(Message msg, long delayMillis)
sendMessageAtTime(Message msg, long uptimeMillis)
这么多方法都可以发送消息,但仔细观察源码却发现最终都调用了 sendMessageAtTime 方法,sendMessageAtTime 又调用了 MessageQueue 的 enqueueMessage(msg, uptimeMillis),这会可能想了 MessageQueue 是干嘛的?它与 Handler 是什么关系?
稍后再说它们之间的关系。(包括 Looper 及 Looper 和他们之间的关系)
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;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
找到这个 MessageQueue 是从 Handler 的构造方法中通过 Looper 获取并被赋的值。
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;
}
那么 Looper 是干啥的呢?
- Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call {@link #prepare} in the thread that is to run the loop, and then {@link #loop} to have it process messages until the loop is stopped.
- 用于为线程运行消息循环的类。线程默认情况下没有与它们相关的消息循环; 创建一个,在要运行循环的线程中调用{@link #prepare},然后{@link #loop}让它处理消息,直到循环停止。
简单说 Looper 用来轮训和分发消息的,那消息从哪来来呢?当然是从 MessageQueue 中获取,上面的解释了 Looper 在线程中的使用方法,先调用 prepare(boolean quitAllowed) ,再调用 loop(),先看下 prepare 方法,可以看出 Looper 是通过此静态方法创建的。
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));
}
在 Looper 的构造中创建了 MessageQueue ,到此我们找到了 MessageQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
MessageQueue 顾名思义就是消息队列,看下它的 enqueueMessage(Message msg, long when) 方法,也就是入队方法
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;
}
接下来看下 loop()方法,此方法中有一个 for (;;) 死循环,它不断地从 MessageQueue 的 next() 方法中取消息,没有消息就 return ,其中 msg.target.dispatchMessage(msg); 方法很关键,Message 调用自己的 target 把自己传了进去,我们看下这个 target 是个什么东东?
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
点进去 Message 类发现 target 是定义在 Message 中的一个变量,是一个 Handler,那么这个 target 是哪个 Handler 呢?我们可以回到 Handler 的 enqueueMessage 方法,这个方法就是上面说的 Handler 发送消息最终要调用的那个方法,可以看到 msg.target = this; 这句,Handler 把自己赋值给了 Message 的 target,由此可见从Looper 中轮训到的消息通过 Message对象 又交给了 Handler 的 dispatchMessage(msg) 方法来处理了。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
看下 dispatchMessage 这个方法,这个方法就是最终处理从消息的方法,这里首先是判断 Message 的 callBack 不为空就交给 Message 的 handleCallback 处理,否则如果 Handler 的 mCallback 不为空就交给 mCallback.handleMessage 处理,如果它也为空,就调用 handleMessage(msg) 处理,其实这个方法就是我们平时使用 Handler 时要重写的那个方法,它在 Handler 中是一个空方法。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
下面这几个方法都是走的 Message 的 handleCallback 方法处理的
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
sendMessageDelayed(getPostMessage(r), 0);
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
至此其实整个流程就走完了,但是上面还有个疑问没说,就是 Handler、Looper、MessageQueue、Message 之间的关系。
再回到 Looper 的 prepare 方法和构造函数 ,prepare 方法中创建 Looper 对象,并将其存入 ThreadLocal 中,在创建之前先从 ThreadLocal 中获取一下,如果有值就抛出异常,一个线程只能对应一个 Looper ,在其构造方法中初始化了一个消息队列 MessageQueue 和一个线程 Thread。从这可看出:一个 Looper 对应着一个消息队列以及当前线程。 而 Looper 是在 Handler 构造函数中调用创建的。
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
总结一下:
一个 Handler 对应一个 Looper
一个 Looper 对应一个 MessageQueue
一个 Looper 对应当前线程 Thread
至于 ThreadLocal 可以看做是一个容器,容器里面存放着属于当前线程的变量,每一个线程都可以独立地改变自己的 ThreadLocal 中存储的变量,并且不会影响其它线程所持有的对应的变量。深入理解可参考
https://droidyue.com/blog/2016/03/13/learning-threadlocal-in-java/