handle:是發(fā)送消息咪惠,處理消息
looper:是輪詢消息
messageQueen:消息隊(duì)列
程序的啟動(dòng)有個(gè)主線程,也就是我們說(shuō)的ui線程,ActivityThread線程有個(gè)main方法,在里面調(diào)用了looper的啟動(dòng)。
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線程是系統(tǒng)給我們寫了looper的創(chuàng)建,但是我們自己寫的線程是沒(méi)有開(kāi)啟消息循環(huán)的,必須要自己調(diào)用Looper.prepare(), 然后調(diào)用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里面,這個(gè)里面存在一個(gè)類似于map結(jié)構(gòu)的model,將looper與thread作為<k,value>傳遞進(jìn)去。
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是如何聯(lián)系的:
handle的構(gòu)造方法里面存在
public Handler(Callback callback, boolean async) {
....
mLooper = Looper.myLooper(); //獲取到當(dāng)前線程里面的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出來(lái)的,可以直接獲取
mCallback = callback;
mAsynchronous = async;
}
Looper里面:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}