Looper 源码分析
Looper:
构造方法初始化mLocalThread、mQueue。static prepare(): 从
sThreadLocal取出当前此案称·线程已初始化的Looper对象,如果没有初始化Looper对象并存入sThreadLocal。myLooper(): 返回
sThreadLocal中当前线程的Looper对象loop(): 调用
muLooper()取得当前线程的Looper对象,再从Looper对象中去的mQueue,然后开启死循环不断调用mQueue.next()方法取得Message对象从Message对象中获取发送该消息的Handler对象,再调用Handler的dispatchMessage()方法,将消息发送到Handler的handleMessage()方法中让用户进行处理。Message: 用于传输的消息实体类
MessageQueue:
单向链表实现的队列
enqueueMessage()将消息加入队列
newxt()从队列中取出消息Handler:
消息辅助类,主要功能向消息池发送各种消息事件
sendMessage(): 向消息队列发送消息
handleMessage():
dispatchMessage()方法将从队列中取出的消息发送到此。让用户进行处理dispatchMessage(): 系统调用将从消息队列取出的消息发送给
handleMessage()处理
主要代码
Looper.java
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
// 循环取出队列中消息去处理
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();
// ...
msg.target.dispatchMessage(msg);
// ...
}
Handler.java
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}