handle:是發送消息,處理消息
looper:是輪詢消息
messageQueen:消息隊列
程序的啓動有個主線程,也就是我們說的ui線程,ActivityThread線程有個main方法,在裏面調用了looper的啓動。
ActivityThread:
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
ui線程是系統給我們寫了looper的創建,但是我們自己寫的線程是沒有開啓消息循環的,必須要自己調用Looper.prepare(), 然後調用Looper.loop();
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
Looper是如何與線程綁定的呢?
ThreadLocal<Looper>, Looper.prepare方法裏面,我們看到ThreadLocal.set方法將looper傳遞到Threadlocal裏面,這個裏面存在一個類似於map結構的model,將looper與thread作爲<k,value>傳遞進去。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
handle,looper與messagequeue是如何聯繫的:
handle的構造方法裏面存在
public Handler(Callback callback, boolean async) {
....
mLooper = Looper.myLooper(); //獲取到當前線程裏面的looper。
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; //messagequeue在looper裏面new出來的,可以直接獲取
mCallback = callback;
mAsynchronous = async;
}
Looper裏面:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}