Android Looper源码分析
//该类管理消息队列 负责消息循环
class Looper{
//sThreadLocal将该类与当前线程绑定 学过Java EE的童鞋对此类一定很是熟悉
private static final ThreadLocal sThreadLocal = new ThreadLocal();
//消息队列 维护消息
final MessageQueue mQueue;
/./当前Looper对象的引用
private static Looper mMainLooper = null;
// 初始化Looper对象将Looper对象与当前线程绑定
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
//Looper构造函数 初始化消息队列 获取当前线程的引用...完成初始化
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
//获取与UI线程绑定的Looper对象 默认情况下 只有UI线程 系统才会为其开启Looper
private synchronized static void setMainLooper(Looper looper) {
mMainLooper = looper;
}
//获取与当前线程绑定的Looper对象
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
//消息循环
public static final void loop() {
//获取与当前线程绑定的Looper对象
Looper me = myLooper();
//消息队列
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
msg.target.dispatchMessage(msg);
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
msg.recycle();
}
}
}
}
Looper源码不是很长 很好分析
建议大家去阅读Adnroid源码 分析之