android的消息机制,我们日常开发中就会经常用到,因为Android的UI线程的限制,不能再UI线程做耗时操作,那么就会需要开启新线程进行耗时操作,当完成耗时操作这时就需要通过消息来通知UI线程完成UI的更新,在Android中为我们提供了Handler,当然只靠Handler并不能完成这一系列的操作还需要Thread,MessageQueue,Message来共同完成,那么通过源码来分析到底消息是怎么完成的。
ThreadLocal
ThreadLocal在消息的传递中起到了很重要的作用,还是需要了解一下,ThreadLocal的作用是让每一个线程中的同一个对象的数据独立起来,假设有三个线程在线程中都去修改这个对象的值,最后我们会得到三个不同的值,他们之间并不会相互干扰,实现通过set/get方法。
set:取出线程的ThreadLocal,把值放入内部的一个Entry[]数组中。
get:取出线程的ThreadLocal,通过哈希得到索引,取出数组中的内容。
Handler的工作原理
先从Handler的构造方法开始
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中的到一个mLooper实例,这个Looper对象是一个ThreadLocal的Looper,所以是当前线程的。同时得到Looper中的MessageQueue实例mQueue。
了解了构造方法向最熟悉的sendMessage看去,最终会执行sendMessageAtTime
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方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
方法中会处理msg的内容,调用MessageQueue的enqueueMessage方法。这里先暂时放Handler一下。
MessageQueue
上边Handler调用了enqueueMessage方法那就从这个方法看起
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 {
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被当作一个单链表的结构,这个方法主要就是进行单链表的插入操作。
这里可能就会有疑问我们只是把msg插进来,但是并没有消耗掉,那么是在哪处理的消息呢,我们看next方法:
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;
}
}
可以看到这个方法中有个for循环会无限循环,当没有消息的时候会一直阻塞在那,当有消息时会返回这个消息并把它删除。
看到这里我们知道了消息是怎么存取的那么是在哪里把消息取出来使用的呢,这就要看到Looper中了。
Looper
先从Looper的构造方法看起
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到Looper会创建一个MeesageQueue实例,还会保存当前线程。构造方法是一个私有方法说明不可被new出来,需要通过其他的方式创建。
我们知道Handler需要Looper.prepare();
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的实例并与当前的线程绑定,之前我们已经讲过了ThreadLocal。创建完了Looper但是还没有开启消息循环,还是接受不到消息,这时候需要调用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();
}
}
方法也会是一个死循环,会调用MessageQueue的next方法得到消息,只有当next方法返回为null是才能跳出循环,如果没有消息则会阻塞在那里等待退出或者新消息到来,当有消息到来msg.target.dispatchMessage(msg);
msg.target得到handler实例,调用handler的dispatchMessage方法。
handler再看
我们又回到handler的代码中,这时又回到了handler中
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
我们来看处理消息的流程,先判断设诶设置过msg.callback,设置过的话执行handleCallback,这是通过post方法设置的。在判断mCallback,设置过执行mCallback.handleMessage,这是为了当创建Handler不想继承创建子类时使用。其余情况则都会执行handleMessage方法,我们需要重写这个方法,在这个方法中我们也就接受到了结果。
小结
在主线程new Handler 则handleMessage在主线程。
Loop.prepare在子线程,则创建的Looper中的线程是子线程,Handler发消息取出的Looper是根据当前线程的所以是子线程的Looper和MessageQueue。
Looper创建MessageQueue,Looper.prepare创建Looper并与调用的线程绑定。
Looper.loop开启消息循环。
至此android的消息机制讲解完毕。对于android消息机制的理解会更佳深入。