Message类的obtain方法
- 消息队列顺序的维护是使用单链表的形式来维护的
- 把消息池里的第一条数据取出来,然后把第二条变成第一条
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
sPoolSize--;
return m;
}
创建Handler对象时,在构造方法中会获取Looper和MessageQueue的对象
public Handler() {
...
//拿到looper
mLooper = Looper.myLooper();
...
//拿到消息队列
mQueue = mLooper.mQueue;
mCallback = null;
}
查看myLooper方法体,发现Looper对象是通过ThreadLocal得到的,在查找ThreadLocal的set方法时发现
- Looper是直接new出来的,并且在Looper的构造方法中,new出了消息队列对象
sThreadLocal.set(new Looper());
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
- sThreadLocal.set(new Looper())是在Looper.prepare方法中调用的
prepare方法是在prepareMainLooper()方法中调用的
public static final void prepareMainLooper() {
prepare();
...
}
在应用启动时,主线程要被启动,ActivityThread会被创建,在此类的main方法中
public static final void main(String[] args) {
...
//创建Looper和MessageQueue
Looper.prepareMainLooper();
...
//轮询器开始轮询
Looper.loop();
...
}
Looper.loop()方法中有一个死循环
while (true) {
//取出消息队列的消息,可能会阻塞
Message msg = queue.next(); // might block
...
//解析消息,分发消息
msg.target.dispatchMessage(msg);
...
}
Linux的一个进程间通信机制:管道(pipe)。原理:在内存中有一个特殊的文件,这个文件有两个句柄(引用),一个是读取句柄,一个是写入句柄
主线程Looper从消息队列读取消息,当读完所有消息时,进入睡眠,主线程阻塞。子线程往消息队列发送消息,并且往管道文件写数据,主线程即被唤醒,从管道文件读取数据,主线程被唤醒只是为了读取消息,当消息读取完毕,再次睡眠
Handler发送消息,sendMessage的所有重载,实际最终都调用sendMessageAtTime
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
...
//把消息放到消息队列中
sent = queue.enqueueMessage(msg, uptimeMillis);
...
}
enqueueMessage把消息通过重新排序放入消息队列
final boolean enqueueMessage(Message msg, long when) {
...
final boolean needWake;
synchronized (this) {
...
//对消息的重新排序,通过判断消息队列里是否有消息以及消息的时间对比
msg.when = when;
Message p = mMessages;
//把放入消息队列的消息置为消息队列第一条消息
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked; // new head, might need to wake up
} else {
//判断时间顺序,为刚放进来的消息寻找合适的位置
Message prev = null;
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
msg.next = prev.next;
prev.next = msg;
needWake = false; // still waiting on head, no need to wake up
}
}
//唤醒主线程
if (needWake) {
nativeWake(mPtr);
}
return true;
}
Looper.loop方法中,获取消息,然后分发消息
//获取消息队列的消息
Message msg = queue.next(); // might block
...
//分发消息,消息由哪个handler对象创建,则由它分发,并由它的handlerMessage处理
msg.target.dispatchMessage(msg);
message对象的target属性,用于记录该消息由哪个Handler创建,在obtain方法中赋值