版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:[https://www.jianshu.com/p/69a04c5d5fc1)
要想说清楚Handler消息机制原理,先得搞清楚消息机制中的几个类,以及它们的关系
public class Handler
public final class Looper
public final class MessageQueue
public final class Message implements Parcelable
先说说Looper类,它有一个静态变量sThreadLocal和myLooper()的静态函数
static final ThreadLocal sThreadLocal = new ThreadLocal();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
public static void prepare() {
prepare(true);
}
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));
}
sThreadLocal对象为线程局部对象,简单来说通过它的get函数每个不同的线程都会获取到唯一的对象为T类型的变量,这里面T的类型为Looper类型,所以每个Thread里面通过sThreadLocal的get函数都能获取到唯一的Looper变量。ThreadLocal的原理是什么,就是根据ThreadLocalMap进行保存值,而ThreadLocalMap对象又保存在Thread中。
言规正传,通过以上的分析我们知道了Looper调用myLooper()就是获取到当前Thread的Looper对象(在第一次调用myLooper()之前需要先调用prepare())。
Looper类里面有一个类型为MessageQueue的成员变量mQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在讲MessageQueue之前,先说说Message,Message也是我们常用的,经常通过obtain获取Message
public final class Message implements Parcelable {
public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
public int sendingUid = -1;
/*package*/ long when;
/*package*/ Bundle data;
/*package*/ Handler target;
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
/*package*/ Message next;
}
Message中有一个重要的指向下一个Message的next引用。这就很像数据结构中的单链表的节点。实际上Message存储在MessageQueue中就是以单链表的形式保存的,同时也是有序的。以Message中的long when的大小进行从小到大排序。
同时还要一个Handler target对象,表示该消息最终由哪个Handler处理。
现在来说MessageQueue,MessageQueue中有两个重要的函数enqueueMessage()和next(),enqueueMessage是向消息队列中插入一条消息,以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.
//如果mMessages消息为空,或者when为0或者when小于mMessages的when,插入在表头
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;
//否则找到一个时间大于when的Message的前面插入
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;
}
很简单,以when为大小,有序插入到mMessages为表头的链表中。
next()函数就更简单了,取出mMessages表头中的消息,如果当前时间小于表头Message时间,则先等待msg.when-currentTime时间,然后取出表头消息。
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;
}
nextPollTimeoutMillis = 0;
}
}
如其名MessageQueue就是一个消息队列的数据结构,里面有插入,查询,删除等操作。
那么又是谁在使用MessageQueue呢,当时是Handler了。我们经常用到的Handler里的sendMessage最终就是调用MessageQueue的enqueueMessage函数,向队列中插入一条消息。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return 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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//注意这句,将发送消息的Handler赋值给Message对象,在Looper循环的时候就能找到对应的Handler处理消息
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler中的mQueue对象是一个MessageQueue类型,它是谁赋值的呢
final Looper mLooper;
final MessageQueue 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;
}
可以看到它引用的是Looper里面的mQueue。
这里我们可以总结下,一个Thread里面只有一个Looper,主线程的Looper就是sMainLooper。每个Looper里面有一个MessageQueue。一个Thread里面Handler可以有很多个实例对象,可以new很多个。但是它们最终指向的Looper对象只会有一个,MessageQueue也只会有一个。所有通过Handler发送的消息,最终都是插入到当前Thread对应的Looper中的MessageQueue中,且以时间进行排序。
那么最后来看看Looper的消息循环
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 (;;) {
//调用MessageQueue的next()函数获取到Message
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丢给msg里面的Handler对象进行处理。
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()函数获取到Message,然后将msg丢给msg里面的Handler对象进行处理。这样消息就最终回到了Handler处理,我们来看看Handler的dispatchMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
//如果Handler的mCallback不为空先调用mCallback处理,返回true,直接return
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
/**
* Subclasses must implement this to receive messages.
*这就是new Handler的时候实现的handleMessage处理消息
*/
public void handleMessage(Message msg) {
}
如果msg的callback不为空,则调用callback处理。否则判断Handler的mCallback是否能处理,否则调用handleMessage处理消息。
以上就是Handler消息机制,还是比较简单的。