Android的消息机制简介
Handler是Android消息机制的上层接口,在开发过程中只需要和Handler交互即可。Handler的使用过程很简单,通过他可以轻松的将一个任务切换到Handler所在的线程中去执行。Android的消息机制主要指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。Handler的创建的时候会采取当前线程的Looper来构造消息循环系统,线程默认是没有Looper的,如果需要使用Handler就必须为线程创建Looper。在UI线程中,ActivityThread在被创建时就会初始化Looper,这就是我们在主线程中默认可以使用Handler的原因。
Android的消息机制流程
首先我们讲讲常用到的Handler与Message,Handler经常用于UI的更新。因为主线程只能进行UI更新,所以在子线程中进行耗时的网络操作等,将子线程运行的结果设置到Message这个结构中,Handler发送message到MessageQueue中,Looper.loop()方法使MessageQueue进行循环,按顺序交给Handler中handleMessage方法来更新UI。
注意点1:Handler的创建必须有Looper存在。主线程中Looper已经完成初始化。在其他线程中创建handler就需要自己创建Looper。否则会出现这样的提示 "Can't create handler inside thread that has not called Looper.prepare()"
注意点2:MessageQueue是单链表的数据结构,并非队列。
MessageQueue的工作原理
MessageQueue是Android中的消息队列,其实它是单链表的数据结构。MessageQueue中最主要的有两个操作:enqueueMessage和next。下面通过源码来分析这两个操作。
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 {
// 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;
}
msg.target就是handler,首先做一些判断hanler是否为空,msg是否被用过,消息循环是否退出了(mQuitting在Looper中会提到)。if (p == null || when == 0 || when < p.when)判断是不是第一个msg。mMessage就是当前消息列表的头。无限循环for (;;),从头开始,找到消息队列中为第一个为null(就是最后一个消息)。


将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;
}
}
如果msg=null,那一直会在这个循环里,直到有新消息来。核心代码在if (msg != null){.......}这段中,主要就是取出消息队列中的第一个消息。
Looper工作原理
Looper在Android消息机制中扮演者消息循环的角色,它会不停地从消息队列中拿出消息交个handler处理,如果没有消息它会一直阻塞。所以当我们处理完所有消息的时候,可以通过quit(直接退出)或quitSafely(把已有想消息处理完后,安全退出)。
我们知道Handler的工作需要初始化Looper,在主线程中Looper是帮我们初始化好的,但是在其他线程需要我们自己初始化Looper,一般我们是这样操作的。
new Thread(){
@Override
public void run(){
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}
looper.prepare中会去初始化Looper,创建消息队列,记录下当前线程
//用到了ThreadLocal
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();
}
Loop.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 {
/*交给handler的dispatchMessage处理*/
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方法中,首先检查一下Looper有没有被创建。然后一个无限循环,不断的取消息队列中的消息数据,然后交给handler的dispatchMessage处理。
quit和quitSafely通过改变消息队列中的mQuitting
public void quitSafely() {
mQueue.quit(true);
}
public void quit() {
mQueue.quit(false);
}
MessageQueue中quit方法
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
当调用quit或者quitSafely时,message.next会返回null,这时就可以退出loop方法中无限循环。
Handler的工作原理
handler在消息机制中的作用是将消息msg或者runnable送到消息队列MessageQueue中,同时looper在循环中会发送消息,返回给handler的dispatchMessage来处理。
sendMessageAtTime
各种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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最后调用enqueueMessage方法,msg.target = this,说明到时候处理消息时也是交给这个handler处理,调用消息队列queue的enqueueMessage方法,消息插入队列。
dispatchMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在Looper.loop()方法中,msg.target.dispatchMessage(msg),消息交给handler处理。首先,检查msg的callback是否为null,callback其实就是handler.post(Runnable r)中的Runnable对象,handleCallback(msg)方法就是让Runnable方法执行run方法。接下来的判断mCallback是否为空,和handler初始化方法有关。handler(Callback c)就会赋值给mCallback,下面的初始化就交给mCallback处理。
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return true;
}
}){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
上面代码中第一个handleMessage中返回true,就不会进入下面处理handleMessage方法中去处理消息,否则交个第二个handleMessage处理消息。
最后总结一下消息机制
首先需要looper.prepare创建Looper,初始化looper中会创建消息队列messageQueue,创建handler,handler发送消息msg给消息队列插入到队尾,Looper.loop()方法,会在消息队列中不断的取队列头msg交个handler去处理消息。
相关小问题
系统为什么不允许在子线程中访问UI?
Android的UI控件是线程不安全的,如果多线程并发访问可能导致UI控件处于不可预见的状态。为何不对UI加上锁机制?1.加上锁机制会让UI访问逻辑变得复杂。2.锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程执行。
网友评论