概述
安卓的消息机制主要是指handler的运行机制以及handler所附带的messageQueue和looper的工作过程,之所以会出现handler主要是因为安卓不允许非UI线程进行UI操作,这个在viewrootimpl中的checkThread()方法中进行了验证:
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
下面就开始看看handler的运行机制是怎样的,在这之前我们得先了解一下threadlocal;
threadlocal
ThreadLocal是一个关于创建线程局部变量的类。 通常情况下,我们创建的变量是可以被任何一个线程访问并修改的。 而使用ThreadLocal创建的变量只能被当前线程访问,其他线程则无法访问和修改。
handler中的looper就保存在ThreadLocal中,这就保证了每个线程的looper对象互不干扰;threadlocal就先了解到这里,go on。
looper的工作原理
looper在安卓消息机制中扮演着消息循环的角色,它会一直监听着messageQueue,一旦messageQueue中有新消息就会立即处理。
先看一下looper的构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在looper的构造方法中初始化了messageQueue并保存当前的线程对象,
我们知道handler的工作需要looper,那么是怎样得到looper的呢?首先在主线程中,我们不用手动去创建,因为在activitythread类中的main()方法已经帮我们创建好了:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
......
Looper.prepareMainLooper();//创建looper对象
ActivityThread thread = new ActivityThread();
thread.attach(false);
......
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();//开始轮询
}
在子线程中我们必须手动去调用looper.prepare()方法创建对象:
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {//保证一个线程只有一个looper
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建looper并保存到ThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}
调用looper.loop()开启轮询监测messagequeue:
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;
......
//开始死循环监测消息
for (;;) {
Message msg = queue.next(); // 从MessageQueue 中读取消息当消息为null的时候跳出循环
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);
}
}
......
msg.recycleUnchecked();
}
}
MessageQueue 工作原理
MessageQueue 也就是我们常说的消息队列,它内部是采用单链表的数据结构来维护消息的,MessageQueue 主要包含插入enqueuemessage()和读取next()操作,其中读取操作伴随着删除操作;
插入操作:
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
// 根据when的比较来判断要添加的Message是否应该放在队列头部。
// 当第一次添加消息的时候,测试队列为空,所以该Message也应该
// 位于队列的头部。
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;
// 不断遍历消息队列,根据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;
}
将Message加入到消息队列中的操作也很简单,就是遍历消息队列中的所有消息,根据when的比较找到适合添加Message的位置。看一下next()方法:
Message next() {
...
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) {
// 循环遍历出第一个异步消息,这段代码可以看出障栅会拦截所有的同步消息。
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
// 当Message还没到被执行时间的时候,记录下一次要执行该Message的时间点。
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 {
// 从队列中取出该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);
// 标记该Message正处于使用状态,然后返回Message。
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
...
}
}
可以发现next方法是一个无限循环的方法,如果队列中没有消息,就会一直阻塞在这里,当有新消息的时候,就返回这条消息并将消息从队列中移除;
handler的工作原理
handler既是消息的发送者,也是消息的消费者,作为发送者,它最后通过调用sendMessageAtTime()方法将消息发送出去,作为消费者,它通过调用dispatchMessage()来处理消息;
先看看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);
}
发送消息的核心方法(所谓的发送消息其实就是把Message加入队列中),方法内部调用了MessageQueue.enqueueMessage(Message msg, long uptimeMillis)执行入列操作。
再看看dispatchMessage()方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// callback实际上就是Runnable对象
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handler处理消息的过程:
首先判断message的callback是否为null,不为null就执行andleCallback()方法;
private static void handleCallback(Message message) {
message.callback.run();
}
然后判断mCallback 是否为null,不为null的话,就执行mCallback 的
handleMessage()方法,Callback是一个接口;
public interface Callback {
public boolean handleMessage(Message msg);
}
通过Callback 可以这样创建handler,Handler h = new Handler(callback);用callback来创建handler的实例不需要派生出handler的子类;
最后调用handleMessage()方法,该方法可能被重写也可能是默认的,这都取决于你:
/**
* Subclasses must implement this to receive messages.
*/
//自己处理业务逻辑
public void handleMessage(Message msg) {
}
流程图:
主线程的消息循环
文章开始已经说过主线程在ActivityThread的main方法中已经为我们创建好了looper对象和messagequeue,然后ActivityThread还需要一个handler来与messagequeue进行交互,这个handler就是ActivityThread.H,它内部定义了一组消息类型,主要包括四大组件的启动和停止等过程;
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
public static final int PAUSE_ACTIVITY = 101;
public static final int PAUSE_ACTIVITY_FINISHING= 102;
public static final int STOP_ACTIVITY_SHOW = 103;
public static final int STOP_ACTIVITY_HIDE = 104;
public static final int SHOW_WINDOW = 105;
public static final int HIDE_WINDOW = 106;
public static final int RESUME_ACTIVITY = 107;
public static final int SEND_RESULT = 108;
public static final int DESTROY_ACTIVITY = 109;
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int NEW_INTENT = 112;
public static final int RECEIVER = 113;
public static final int CREATE_SERVICE = 114;
public static final int SERVICE_ARGS = 115;
public static final int STOP_SERVICE = 116;
ActivityThread通过applicationthread和AMS进行进程间的通信,AMS以进程间的通信完成ActivityThread的请求后会回调ActivityThread的Biner方法,然后applicationthread会向H发送消息,H收到消息后会将applicationthread中的逻辑切换到ActivityThread中去执行,即切换到主线程中,这个过程就是主线程的消息循环模型。