Android的消息机制
–主要是指 Handler 的运行机制 和 MessageQueue 、 looper 的工作过程。
MessageQueue
MessageQueue 消息队列,用来存储消息,虽然称为消息队列,但是它的存储结构是采用 单链表的数据结构来存储消息队列的。
包含两个操作插入(enqueueMessage) 和 读取(next)
enqueueMessage :往消息链表 中插入一条信息
next:从消息列表中读取一天消息,并将其从消息队列中移除,next方法是一个无限循环的方法,如果消息列表里没有消息,那么会一直阻塞在这里。
Looper
Looper 消息循环,用来处理消息。
Looper 会不停的从 MessageQueue 中查看是否有新的消息,如果有新消息就会立即处理
Looper.java
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在 Looper 的构造方法会创建一个MessageQueue,消息队列,然后将当前线程的对象保存起来。
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
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.prepare() 不能被调用两次?
答:因为每次调用 Looper.prepare() 的时候的都会判断 ThreadLocal是否已经存储当前的 Looper 对象,如果已经存在就会抛出异常。
/**
* 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();
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();
}
}
loop 方法就是一个死循环,跳出死循环的方法,是 MessageQueue的 Next 方法为空,即queue.next() 为空。Looper 调用 quit 方法或者 quitSafely 方法,通知消息队列退出,会使 MessageQueue 的 next 方法 返回为空。
loop 调用 MessageQueue 的 next 方法获取新的消息,如果 没有消息,next 方法会一直阻塞在那里,导致 loop 方法也会一直阻塞在那里。 如果 next 方法返回了新的消息,Looper 就会处理新的消息,调用 msg.target.dispatchMessage(msg),msg.target 就是发送这条消息的 Handler 对象(Handler 中有讲解)。这样就把代码逻辑切换到指定线程去执行了。
- ThreadLocal
线程内部的数据存储类, 通过它可以在指定的线程存储数据,而且存储后,只能在指定线程获取存储的数据,其他线程无法获取。
应用:当某些数据是以线程为作用域,并且不同线程具有不同数据
存在Looper中,并不是线程,作用是在每个线程中存储数据
问题:Handler内部是如何获取当前线程的 Looper 的?
Handler.java
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class