Android的消息机制是Android系统中很重要的一块,在Android系统中运用的非常多,比如Activity的启动以及Activity的生命周期都是通过消息机制完成的。
流程
首先看一下消息机制的大致流程:
从上图中,我们可以看到消息机制主要分为四大块:Handler,Message,MessageQueue,Looper,下面我们分为对这4大块进行讲解。
Message
message是一个消息对象,它相当于链表的节点,里面存储了消息数据和下一个消息对象信息:
public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
public int sendingUid = -1;
/*package*/ static final int FLAG_IN_USE = 1 << 0;
/** If set message is asynchronous */
/*package*/ static final int FLAG_ASYNCHRONOUS = 1 << 1;
/** Flags to clear in the copyFrom method */
/*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;
/*package*/ int flags;
/*package*/ long when;
/*package*/ Bundle data;
/*package*/ Handler target;
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
/*package*/ Message next;
从图中我们可以看到,好多字段都是我们以前用过的。
Handler
handler是负责发送和处理消息的,发送的流程如下:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
Message message = new Message();
message.what = 0;
handler.sendMessage(message);
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) {
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);
}
这里是将消息进行部分处理,然后通过MessageQueue的enqueueMessage将消息加入到但链表中。
至于消息的处理,它是通过Looper循环器从MessageQueue中取出消息,然后发送到Handler中的dispatchMessage方法,这个稍后会在Looper中分析到,我们先看看dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看到最终调用了handleMessage方法,就是我们new Handler对象会重载的方法,在里面处理一系列数据。
Looper
looper:循环调度器,是负责不断的从MessageQueue中取出Message,一个线程只能有一个Looper:
public static void prepare() {
prepare(true);
}
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));
}
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
接下来,让我看看循环调度器是怎么取出消息的?
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
}
}
}
从上面我们可以看到他开启了一个无限循环,不断的从Message Queue中取消息,当消息不为空的时候,他会回调Handler的dispatchMessage的方法,就是我们上面Handler所说的。
MessageQueue
messageQueue:消息队列,负责消息的插入和取出。
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
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;
}
}
return true;
}
Message next() {
for (;;) {
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
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) {
if (now < msg.when) {
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;
msg.markInUse();
return msg;
}
} else {
nextPollTimeoutMillis = -1;
}
if (mQuitting) {
dispose();
return null;
}
}
}
这就是对单链表的操作,是按照when排序的。这里要注意的是nativePollOnce(ptr, nextPollTimeoutMillis)这个方法,这是调用了native层的方法,利用epoll机制在之前建立的管道上等待数据写入,接收到数据后马上读取并返回结果,简单的来说当没有消息时,会阻塞在这里,释放cpu资源,进入休眠状态,等待通知,当有消息的时候,会继续往下读取消息,如果读到消息,将返回给looper循环调度器
Handler引起的内存泄漏问题
我们都知道非静态内部类会持有外部类的引用,在activity的声明Handler的内部类,也会持有activity对象的引用,当activity退出而Handler正在处理任务时就会造成activity的泄漏问题,此时gc扫描时,该activity的对象还在被使用,所以不能回收掉。解决方法:将非静态类修改为静态内部类,在其内部使用弱引用。
private static class UpdateHandler extends WeakHandler {
public UpdateHandler(TopSiteView ref) {
super(ref);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
TopSiteView topSiteContext = getRef().get();
if (topSiteContext != null) {
topSiteContext.initView();
}
}
}
public class WeakHandler extends Handler {
protected WeakReference mReference;
public WeakHandler(T ref) {
mReference = new WeakReference(ref);
}
public WeakHandler(Looper looper, T ref) {
super(looper);
mReference = new WeakReference<>(ref);
}
protected WeakReference getRef() {
return mReference;
}
}
FAQ
一个线程中能有几个Handler?如何保证唯一?
1.一个线程中可以创建多个Handler,就像我们可以在每个activity中创建一个Handler,但是Looper只能有一个,这个在我们上面分析Looper的时候也说了,就相当于一个Looper对应一个MessageQueue,一个MessageQueue对应多个Message,而Message中的target持有Handler对象,同理一个线程可以创建多个Handler.
2.ThreadLocal保证唯一,原因稍后研究。
主线程的Looper和子线程的Looper有什么区别?
通过上面的源码分析,他们的创建过程prepare()和prepareMainLooper()可以看到他们只有quitAllowed参数是不一样的,那我们可以往下追踪一下
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
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);
}
}
从源码中可以知道mQuitAllowed只在quit方法中使用到了,从这里我们就可以知道一个区别:主线程的Looper是不可以退出的,而子线程Looper是可以退出的,这个方法往下的操作就是删除消息队列里的内容。