Handler消息機(jī)制主要涉及以下類:
- Handler
- Looper
- MessageQueue
- Message
Handler必須創(chuàng)建在有Looper的線程中裂允,Looper.prepare()即在該線程創(chuàng)建Looper。
- Handler發(fā)送消息到MessageQueue涵妥,調(diào)用MessageQueue的enqueueMessage(),將消息按時(shí)間順序插入到鏈表中柿估。
- Looper調(diào)用loop()開啟無限循環(huán)跳夭,內(nèi)部調(diào)用MessageQueue的next()取消息。內(nèi)部調(diào)用nativePollOnce泼返,作用是設(shè)置一個(gè)定時(shí)的睡眠硝逢。根據(jù)nextPollTimeoutMillis來判斷睡眠:
- nextPollTimeoutMillis = 0 :無需睡眠,直接返回绅喉。
- nextPollTimeoutMillis > 0 :睡眠超過nextPollTimeoutMillis渠鸽,就返回。
- nextPollTimeoutMillis = -1 :一直睡眠柴罐,直到其他線程喚醒徽缚。
- 取出消息后,則根據(jù)msg.target對(duì)應(yīng)的handler革屠,調(diào)用dispatchMessage來處理消息凿试。當(dāng)Looper調(diào)用了quit或者quitSafely排宰,會(huì)導(dǎo)致取出的消息為null,則退出looper循環(huán)那婉。
參考:
http://www.reibang.com/p/a7559af33986
http://www.reibang.com/p/13c8a66d3b5c