概述
Android系统某种意义上也可以说成是一个以消息驱动的系统。消息机制涉及/Looper/Handler/MessageQueue/Message这4个类。
模型
消息机制主要包含:
- Message:消息分为硬件产生的消息(如按钮、触摸)和软件生成的消息;
- MessageQueue:消息队列的主要功能向消息池投递消息(
MessageQueue.enqueueMessage)和取走消息池的消息(MessageQueue.next); - Handler:消息辅助类,主要功能向消息池发送各种消息事件(
Handler.sendMessage)和处理相应消息事件(Handler.handleMessage); - Looper:不断循环执行(
Looper.loop),按分发机制将消息分发给目标处理者。
大致流程
- Handler通过sendMessage()发送Message到MessageQueue队列;
- Looper通过loop(),不断提取出达到触发条件的Message,并将Message交给target来处理;
- 经过dispatchMessage()后,交回给Handler的handleMessage()来进行相应地处理。
- 将Message加入MessageQueue时,处往管道写入字符,可以会唤醒loop线程;如果MessageQueue中没有Message,并处于Idle状态,则会执行IdelHandler接口中的方法,往往用于做一些清理性地工作。
简单demo
public class Demo extends Thread{
private Handler mHandler;
@Override
public void run() {
super.run();
Looper.prepare();
mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
//消息处理
}
};
Looper.loop();
}
}
Looper类的分析
Looper.prepare()
public static void prepare() {
prepare(true);
}
//quitAllowed true表示可以退出 false表示不可以退出
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建Looper对象,并保存到当前线程的TLS区域
sThreadLocal.set(new Looper(quitAllowed));
}
sThreadLocal 是ThreadLocal
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
ThreadLocal
ThreadLocal是线程本地存储区(TLS),每个线程都有自己私有的本地存储区域,不同的线程之间是不能相互访问的。
ThreadLocal中常用的方法
public void set(T value) {
Thread t = Thread.currentThread();//获取当前线程
ThreadLocalMap map = getMap(t);//查找当前线程的存储区域
if (map != null)
map.set(this, value);//保存数据到当前线程中
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
//返回当前线程存储区域中的数据
return result;
}
}
return setInitialValue();
}
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
sThreadLocal的get和set方法其实操作的是Looper
ThreadLocal就大致介绍到这里。
Looper.prepare()
Looper.prepare()在每个线程只允许执行一次,该方法会创建Looper对象,Looper的构造方法中会创建一个MessageQueue对象,再将Looper对象保存到当前线程TLS。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//创建MQ对象
mThread = Thread.currentThread();//记录当前线程
}
在ActivityThread类中有一个prepareMainLooper方法与prepare功能类似
@Deprecated
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.loop()
public static void loop() {
final Looper me = myLooper();//获取looper对象
final MessageQueue queue = me.mQueue; //获取Looper对象中的MQ
Binder.clearCallingIdentity();
//确保在权限检查时是基于本地进程,而不是调用进程
final long ident = Binder.clearCallingIdentity();
for (;;) { //进入loop的循环方法
Message msg = queue.next(); // might block
if (msg == null) { //没有消息的话退出循环
return;
}
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
...
try {
msg.target.dispatchMessage(msg);//用于分发消息
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
//恢复调用者信息
final long newIdent = Binder.clearCallingIdentity();
msg.recycleUnchecked();//将message放入消息池
}
}
loop()进入循环模式,不断重复下面的操作,知道没有消息退出循环
- 读取MQ的下一条message
- 把message分发给相应的target
- 把分发后的message放回到消息池,以便重复利用
Looper.quit()
public void quit() {
mQueue.quit(false);//消息移除
}
public void quitSafely() {
mQueue.quit(true);//安全移除消息
}
MessageQueue.quit()
void quit(boolean safe) {
// 当mQuitAllowed为false,表示不运行退出,强行调用quit()会抛出异常
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);
}
}
消息退出的方式:
- 当safe==true ,只移除尚未触发的所有消息,对正在触发的消息不移除
- 当safe==flase,移除所有消息
Looper.myLooper()
//获取looper对象
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
Handler类的分析
无参构造
public Handler() {
this(null, false);
}
public Handler(@Nullable Callback callback, boolean async) {
//匿名类、内部类或本地类都必须申明为static,否则会警告可能出现内存泄露
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());
}
}
//必须先执行Looper.prepare(),才能获取Looper对象,否则为null.
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//消息队列
mCallback = callback;//回掉
mAsynchronous = async;//设置消息是否异步处理
}
对于handler的无参数的构造方法,默认是用当前线程中的looper对象,并且callback为bull,且消息时同步处理的。
有参构造
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
有参数构造可以指定looper,callback和消息处理方式,而无参的只能使用当前线程的looper对象。
消息分发
在looper.loop() 中,当发现有消息时,会调用消息目标的dispatchMessage() 方法来分发消息
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
//当callback不为空,回掉callback的run方法
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//调用自身的handleMessage方法
handleMessage(msg);
}
}
消息分发的流程:
- 当
message的回掉方法不为空时,调用callback.run()。其中callback类型时runnable。 - 当
Handler的mCallback成员变量不为空时,回掉mCallback.handleMessage(msg) - 调用
Handler自身的回调方法handleMessage(),该方法默认为空,Handler子类通过覆写该方法来完成具体的逻辑
实际中一般都是第三种,覆写handleMessage()实现自己的业务逻辑。
消息发送
消息发送涉及的方法比较多,但是最终都是调用
MessageQueue.enqueueMessage()
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue.enqueueMessage()
boolean enqueueMessage(Message msg, long when) {
//消息必须有一个target
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {removeMessages
throw new IllegalStateException(msg + " This message is already in use.");
}
if (mQuitting) {//正在退出时,回收message,加入消息池
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//p为null(代表MessageQueue没有消息) 或者msg的触发时间是队列中最早的, 则进入该该分支
msg.next = p;
mMessages = msg;
needWake = mBlocked; //阻塞时需要唤醒
} else {
//将消息按时间顺序插入到MessageQueue。一般地,不需要唤醒事件队列,除非 //消息队头存在barrier,并且同时Message是队列中最早的异步消息。
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;
}
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
MessageQueue是按照Message触发时间的顺序排列的,队头的消息是最早触发的消息。当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证所有消息是按照时间排序的。
其他常用方法
public final Message obtainMessage()
{
return Message.obtain(this);
}
public final void removeMessages(int what) {
mQueue.removeMessages(this, what, null);
}
handler是消息机制中非常重要的辅助类,更多的实现是MessageQueue和message中的方法。
MeaagesQueue类的分析
构造方法
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
//通过native方法初始化消息队列,mPtr是给native代码使用的
mPtr = nativeInit();
}
next() 取消息
Message next() {
final long ptr = mPtr;
if (ptr == 0) {//消息循环结束,直接返回
return null;
}
int pendingIdleHandlerCount = -1; // 循环迭代的第一次设置为-1
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//阻塞操作
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//当消息的handler为空则查询异步消息
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//当异步消息触发时间大于当前时间,则设置下一次轮询的超时时长
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 获取消息并返回
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 {
//没有消息
nextPollTimeoutMillis = -1;
}
//消息正在退出,返回null
if (mQuitting) {
dispose();
return null;
}
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
//只有第一次循环时,会运行idle handlers,执行完成后,重置pendingIdleHandlerCount为0.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // 去掉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);
}
}
}
//重置IdleHandler
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
nativePollOnce是阻塞操作,其中nextPollTimeoutMillis代表下一个消息到来前,还需要等待的时长;当nextPollTimeoutMillis = -1时,表示消息队列中无消息,会一直等待下去。
当处于空闲时,往往会执行IdleHandler中的方法。当nativePollOnce()返回后,next()从mMessages中提取一个消息。
enqueueMessage()
在handler中已经介绍了,这里就不在重复。
其他常用的方法
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
这个移除消息的方法,采用了两个while循环,第一个循环是从队头开始,移除符合条件的消息,第二个循环是从头部移除完连续的满足条件的消息之后,再从队列后面继续查询是否有满足条件的消息需要被移除
小结
MessageQueue是消息机制的Java层和C++层的连接纽带,大部分核心方法都交给native层来处理
Meaages类的分析
消息对象包含的内容
| 变量 | 解释 |
|---|---|
| what | 消息类别 |
| when | 消息发送的时间 |
| arg1 | 参数1 |
| arg2 | 参数2 |
| obj | 消息内容 |
| target | 消息的接收方 |
| callback | 回掉方法 |
消息池
public static final Object sPoolSync = new Object();
把消息加入到消息池的作用。这样的好处是,当消息池不为空时,可以直接从消息池中获取Message对象,而不是直接创建,提高效率。
静态变量sPoolSync的数据类型为Message,通过next成员变量,维护一个消息池;静态变量MAX_POOL_SIZE代表消息池的可用大小;消息池的默认大小为50。
消息池常用的操作方法是obtain()和recycle()。
obtain()
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;//从sPool中取出一个Message对象,并消息链表断开
m.flags = 0; // clear in-use flag
sPoolSize--;//消息池的可用大小进行减1操作
return m;
}
}
return new Message();//当消息池为空时,直接创建Message对象
}
从消息池取Message,再把表头指向next;
recycle()
public void recycle() {
if (isInUse()) {//是否在使用
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
//将不再使用的message加入到消息池
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
将Message加入到消息池的过程,都是把Message加到链表的表头