Android的消息机制主要是指Handler的运行机制,Handler的运行机制需要底层MessageQueue和Looper的支撑。
- Handler:消息的执行者,也可以称之为异步任务的执行者
- Message:消息的封装者,把异步任务,消息码Handler对象等封装成Message对象
- MessageQueue:消息队列,用于保存当前线程的所有消息Message对象的一个列表,内部储存结构为单链表的数据结构
- Looper:循环者,能让工作线程变成循环线程,然后从消息队列中循环读取消息
- ThreadLocal:线程内部数据储存类,通过它可以获取每个线程的Looper,线程默认是没有Looper的,如果在线程内需要使用Handler就必须为线程创建Looper(详见 ThreadLocal工作原理)
1.MessageQueue(消息队列)的工作原理
这里说的消息队列即为MessageQueue,主要包含插入消息和读取消息两个操作,当然读取会伴随着删除。内部实现并不是队列,其实是单链表,单链表在插入和删除上有优势。
接下来看一下插入消息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("MessageQueue", 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 (needWak