Android Handler源碼淺析
相關(guān)對(duì)象
- Handler可以看作CEO碟婆,負(fù)責(zé)消息的處理和發(fā)送吠勘,Handler發(fā)送消息給MessageQueue,涵防,然后Looper取出其中的消息給Handler铜幽。
- Looper,Handler的管家驴剔,可以看作秘書抄沮,負(fù)責(zé)管理MessageQueue,她會(huì)不斷的從MessageQueue中取出消息跋核,交給Handler處理岖瑰。
- MessageQueue是存放消息的隊(duì)列,負(fù)責(zé)存放Handler發(fā)來(lái)的消息了罪。
Looper部分源碼講解
public static void prepare() {
prepare(true);
}
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));
}
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
Looper實(shí)例化是在Looper.prepare()方法中锭环。
小插曲
ThreadLocal是一個(gè)和多線程并發(fā)相關(guān)的類。當(dāng)使用ThreadLocal維護(hù)變量時(shí)泊藕,ThreadLocal為每個(gè)使用該變量的線程提供獨(dú)立的變量副本辅辩,所以每一個(gè)線程都可以獨(dú)立地改變自己的副本,而不會(huì)影響其它線程所對(duì)應(yīng)的副本娃圆。
ThreadLocal維護(hù)了一個(gè)Map集合玫锋,其中鍵為當(dāng)前線程,值就是不同線程的變量讼呢。
ThreadLocal中的方法不多撩鹿。
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
set方法很容易理解,首先獲取當(dāng)前線程悦屏,再用當(dāng)前線程當(dāng)鍵來(lái)獲取map集合节沦,如果map為空,則重新創(chuàng)建一個(gè)map并設(shè)置值進(jìn)去础爬,否則的話甫贯,直接設(shè)置值進(jìn)去。get同理看蚜。
回到主題叫搁。所以Looper的prepare只能獲取當(dāng)前線程的Looper對(duì)象,并且如果已經(jīng)存在一個(gè)Looper對(duì)象則會(huì)報(bào)異常供炎,所以這也說(shuō)明了一個(gè)線程中只能存在一個(gè)Looper對(duì)象渴逻。并且prepare只能調(diào)用一次。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static void loop() {
final Looper me = myLooper();
//此處只展示了關(guān)鍵代碼
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
msg.recycleUnchecked();
}
}
Looper中創(chuàng)建了一個(gè)MessageQueue音诫,并且在Looper的loop方法中惨奕,開啟無(wú)限循環(huán)去遍歷MessageQueue,如果消息不為空竭钝,則將消息發(fā)送給Handler梨撞。這個(gè)msg.target其實(shí)就是Handler對(duì)象。
我們一般都會(huì)重寫Handler的handleMessage方法蜓氨,其中緣由也在源碼里聋袋。
我們不管sendEmptyMessage也好,postDelayed也罷穴吹,最終都會(huì)調(diào)用到一個(gè)方法幽勒。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target = this。這句話中的this就是Handler對(duì)象港令。
同時(shí)把消息放入MessageQueue中啥容。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在Looper的loop方法中锈颗,她把消息用dispatchMessage傳了過(guò)來(lái)。在dispatchMessage中咪惠。優(yōu)先級(jí)有三種击吱。優(yōu)先級(jí)最高的是message自己的callback,然后是Handler的callback遥昧,當(dāng)兩者都沒有的時(shí)候覆醇,就由我們重寫來(lái)處理。這也是我們最常用的一種方法炭臭。
那么Looper是什么時(shí)候啟動(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");
}
其中Looper.prepareMainLooper()和Looper.prepare()等價(jià)。這個(gè)ActivityThread也就是我們所說(shuō)的UI線程鞋仍,Looper在UI線程啟動(dòng)的時(shí)候常摧,就一直在后臺(tái)默默工作了。
思考威创,Handler怎么做到線程切換處理對(duì)象的?
因?yàn)椴煌€程共享內(nèi)存落午,Handler在A線程發(fā)送了一個(gè)消息,然后主線程的Looper在主線程把消息取了出來(lái)肚豺,同時(shí)交給了Handler溃斋,所以Handler一取一存就做到了線程切換。
小結(jié)
其實(shí)看源碼本沒有那么復(fù)雜详炬,有時(shí)候根本不需要抽絲剝繭一條條代碼看盐类,代碼量很多寞奸,難度確實(shí)是有的呛谜。但是我們只要有一個(gè)目標(biāo),有一條主線枪萄,只尋找最關(guān)鍵的代碼隐岛,就能很快的理清它的脈絡(luò)。