概述
Android消息在上层的接口是Handler,Handler所使用的相关的Looper、MessageQueue、ThreadLocal等类。我们经常使用的场景是我们需要做一些像I/O操作、联网等等耗时操作时需要更新Ui线程时需要使用Handler去发消息给UI线程去更新UI。 那Handler、Looper、MessageQueue、ThreadLocal这些类之间关系是怎样的呢?又是是怎么交互的呢?看看下面:
Handler、Looper、MessageQueue、ThreadLocal基本关系
Handler、Looper、MessageQueue是一个整体运作的,当我们使用Handler发送消息时,是像MessageQueue中的单链表中插入一条消息,Looper中的loop方法时阻塞的无限循环方法,当MessageQueue中有消息时就会处理这个消息通知Handler的回调去处理这个消息,直到MessageQueue中没有消息时Looper中的loop方法会继续进入阻塞状态。ThreadLocal可以在不同线程互不干扰的设置和存储数据,也是Handler获取当前线程Looper的关键。除了Ui线程其他线程是默认没有Looper的需要自己去创建,而Ui线程其实是ActivityThread,在ActivityThread的main方法中会调用Looper的prepare和loop方法,所以UI线程可以直接使用Looper。好了,基本关系了解了那我们看一个每个模块的主要方法的工作流程吧。
ThreadLocal工作流程
ThreadLocal中重要的是set和get方法,源码如下:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
可以看到这两个方法都是获取当前Thread,每个Thread中都会有一个ThreadLocalMap用来存储各自线程的数据,如果ThreadLocalMap为null会创建一个ThreadLocalMap并赋值给当前线程。其他相关代码有兴趣的可以自己去看一下。
ThreadLocal可以在不同的线程中维护各自的数据,Looper就是借助了这个特性使用了ThreadLocal去把自己存储到每个Thread的ThreadLocalMap中,这样去获取Looper时可以通过ThreadLocal直接拿到当前线程的Looper。
MessageQueue工作流程
MessageQueue主要用来存放消息,里面的消息队列是一个单链表,主要方法是enqueueMessage和next方法,分别是Handler发送消息时用来将消息插入消息队列的和Looper中loop方法中遍历消息调用的next方法处理消息队列里面的消息,下面我们来看看这两个方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {//判断消息里是否有对应的handler(target存的是handler)
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,Message对象池其实是通过链表的结构组合起来的池。具体的可以看这个链接里面有说道:https://www.jianshu.com/p/8ecacbb97af4 , 里面也提到了Message对象的复用,对应的设计模式享元模式,有兴趣的可以自己去研究。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {//无限循环
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);//没有消息时阻塞在管道的读端,等待有消息时被唤醒
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
next方法里面会无限循环遍历链表,没消息时阻塞,有消息时将消息返回,并将该消息从链表中删除。
Looper工作流程
ActivityThread的main方法会调用Looper.prepareMainLooper(),看一下main方法里面的调用:
Looper.prepareMainLooper();//给UI线程创建Looper
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();//开始UI线程的无限循环处理消息
看Looper里面对应方法prepareMainLooper的源码:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
可以看到prepareMainLooper会调用prepare方法,看一下prepare方法:
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//重复prepare会抛出异常
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
可以看到prepare方法会创建一个Looper对象并调用ThreadLocal的set()方法保存到当前线程的ThreadLocalMap中去,每个线程只有一个Looper,重复prepare会抛出异常。
接下来看看最主要的loop()方法:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();//拿到当前线程的Looper
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//创建Looper时也会创建一个MessageQueue
// 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();//重置ipc标志
final long ident = Binder.clearCallingIdentity();
for (;;) {
//调用MessageQueue的next方法,如果next返回null就会退出loop的循环
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();
}
}
loop会一直循环,next是个阻塞方法,next没有消息时也会将loop方法阻塞,next返回null时,Looper就会退出。next方法有消息返回时,会调用Handler的dispatchMessage(msg)方法。下面看一下Handler。
Handler工作流程
1.先看一下dispatchMessage()方法
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
dispatchMessage()通知回调有三种
(1).先处理message的callback,不为空的话直接run,对应的是handler.post()传过来的Runnable对象
(2).message的callback为null的话,处理handler的创建时传过来的callback,里面重写的handleMessage()方法
(3).直接回调创建Handler是的的内部类里面的handleMessage()方法
图里可以看到逻辑
2.再看一下发送消息
最终都会调用到下面这个方法
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里面插入消息
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
插入后等待Looper去处理即可。
总结
大概介绍了一下Android消息的基本流程,Handler、Looper、MessageQueue之间的协作。里面还有一些细节比如Message的链表结构以及享元模式等等知识点后面再去学习。