Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。MessageQueue翻译为消息队列,顾名思义,它的内部存储了一组消息,以队列的形式对外提供插入和删除的工作。其内部真正是通过单链表的数据结构来存储消息列表的。MessageQueue是一个消息的存储单元,它不能去处理消息,处理消息由Looper来负责,Looper会以无限循环的形式去查找是否有新消息,如果有的话就处理新消息,否则一直等待。Looper中有一个特殊的概念,TreadLocal,它的作用是可以在每一个线程中存储数据。
我们知道,Handler创建的时候会采用当前线程的Looper来构造消息循环系统,那么Handler内部如何获取当前线程的Looper呢,就要使用TreadLocal,TreadLocal可以在不同的线程中互不干扰的存储并提供数据,通过TreadLocal可以轻松获得每一个线程的Looper。要注意的是,线程默认是没有Looper的,如果需要使用Looper就必须为线程创建Looper。主线程(ActivityThread)被创建是会初始化Looper,这就是主线程中默认可以使用Handler的原因。
一、Android的消息机制概述
Handler的主要作用是将一个任务切换到某个指定的线程中去执行。Android中存在这个功能是因为Android只能在主线程中更新UI。如果在主线程中进行耗时操作,会导致ANR。因此,系统子所以提供Handler,主要原因就是为了解决在子线程中无法访问UI的矛盾。
为什么不允许在子线程中访问UI呢,因为Android的UI控件不是线程安全的。如果在多线程中并发访问可能导致UI控件处于不可预期的状态,那么为什么不能UI控件加上锁机制呢?缺点有两个:首先加上锁机制会让UI访问的逻辑变得复杂,其次锁机制会导致UI访问的效率降低,因为锁机制会阻塞某些线程的执行。所以最简单的方法就是用Handler了。
Handler工作原理:
Handler创建时会采用当前线程的Looper来构建内部的消息循环系统,如果当前线程没有Looper那么就会报错。Handler创建完毕后,这个时候其内部的Looper以及MessageQueue就可以和Handler一起协同工作了。然后通过Handler的post方法将一个Runnable投递到Handler内部的Looper去处理,也可以通过Handler的send方法来发送一个消息,这个消息同样会在Looper中去处理。其实post方法也是通过send方法来完成的。
send方法的工作过程:
当Handler的send方法被调用时,它会调用MessageQueue的enqueueMessage方法将这个消息放到消息队列中,然后Looper发现有新消息到来时,就会处理这个消息,最终消息中的Runnable或者Handler的handleMessage方法中被调用。
二、Android的消息机制分析
1.ThreadLocal的工作原理
ThreadLocal是一个线程内部的数据存储类。通过他可以在指定的线程中存储数据,数据存储以后只有在指定的线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。
ThreadLocal的使用场景,一般当某些数据是以线程为作用域并且不同的线程具有不同的数据作用与时就可以考虑使用ThreadLocal了。
比如:对于Handler来说,它需要获取当前线程的Looper,很显然Looper的作用域就是线程,并且不同的线程具有不同的Looper,这个时候通过ThreadLocal就可以轻松实现Looper在线程中的存取。如果不采用ThreadLocal,系统就必须提供一个全局的哈希表供Handler查找指定线程的Looper。这样一来就必须提供一个类似于LooperManager的类了,但是系统并没有这么做,而是使用了ThreadLocal,这就是ThreadLocal的好处。
ThreadLocal的另一个使用 场景就是复杂逻辑下的对象传递。
比如监听器的传递。有时候一个线程中的任务过于复杂,这可能表现为函数调用栈比较深以及代码入口的多样性,在这种情况下,我们有需要监听器贯穿整个线程的执行过程,这时候就可以使用ThreadLocal,ThreadLocal可以让监听器作为线程内的全局变量存在,在线程内部只需要通过get方法就可以获取到监听器。如果不使用ThreadLocal,还可以可能是如下两种方法:第一种是将监听器作为参数的形式在函数调用栈中进行传递;第二种就是将监听器作为静态变量供线程访问。
上述两种方法都具有局限性。第一种方式当函数调用栈很深的时候,通过函数参数来调用监听器对象几乎是不可接受的,这会让程序看上去很糟糕。第二种方式是是可以接受的,但是这种状态不具有扩展线,比如,同时有十个线程并发执行呢,就要提供十个静态的监听器对象,这很显然不好。
案例见书376页。
2.消息队列的工作原理。
Android中的消息队列是指MessageQueue,MessageQueue主要包含两个操作:插入和读取。读取操作本身伴随着删除操作。插入和读取的对应方法分别为enqueueMessage和next,其中enqueueMessage的作用是往消息队列中插入一条数据,而next的作用是从消息队列中取出一条消息并将消息队列移除。尽管MessageQueue叫做消息队列但是其内部不是使用队列实现的,而是通过一个单链表的数据结构来来维护消息队列的。
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;
}
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;
}
}
3.Looper的工作原理
//在线程中创建Looper
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
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
可以在任何地方获取主线程的looper
/**
* Returns the application's main looper, which lives in the main thread of the application.
*/
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
直接退出looper
/**
* Quits the looper.
* <p>
* Causes the {@link #loop} method to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @see #quitSafely
*/
public void quit() {
mQueue.quit(false);
}
设定一个退出标记,然后把消息队列已有的消息处理完毕后再安全退出。
/**
* Quits the looper safely.
* <p>
* Causes the {@link #loop} method to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* However pending delayed messages with due times in the future will not be
* delivered before the loop terminates.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p>
*/
public void quitSafely() {
mQueue.quit(true);
}
开启消息循环队列,是一个死循环,跳出方法就是next方法返回为null,退出时必须让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();
}
}
4.Handler的工作原理
Handler的工作主要包括消息的发送和接受。
发送消息
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;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
处理消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先判断message的callback是否为null,不为null就通过handleCallback来处理callback,message的callBack是一个Runnable对象,实际上是handler的post方法所传递的Runnable参数。
其次检查mCallback是否为null,不是就调用mCallback的handleMessage方法。
private static void handleCallback(Message message) {
message.callback.run();
}
Handler.Callback callback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
};
Handler handler = new Handler(callback);
Callback 意义,可以创建一个Handler的实例并且不要派生Handler的子类。
public interface Callback {
public boolean handleMessage(Message msg);
}
最后调用Handler的HandleMessage方法来处理消息
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
三、主线程的消息循环
Android的主线程就是ActivityThread,主线程的入口方法是Main,在Main方法中会通过Looper.prepareMainLooper来创建主线程的looper以及messagequeue,并通过Looper.loop()俩开启主线程的消息循环。
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
AndroidKeyStoreProvider.install();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
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();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
主线程的消息循环开始以后,ActivityThread还需要一个Handler来和消息队列进行交互,这个handler就是ActivityThread.H,他内部定义了一组消息类型,主要包括四大组件的启动和停止。
private class H extends Handler {
ActivityThread通过ApplicationThread和AMS进行进程间通信,AMS以进程间通信的方式完成ActivityThread的请求后会回调ApplicationThread中的Binder方法,然后ApplicationThread会向H发送消息,H收到消息后会将ApplicationThread中的逻辑切换到ActivityThread中去执行,即切换到主线程中去执行。