1、Loop.prepare():創(chuàng)建Loop對象,初始化Loop中的MessageQueue跟當前的Thread;
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));
}
2、Loop.loop():拿到當前線程Loop對象,在拿到Loop中的消息隊列,for循環(huán)輪詢遍歷消息隊列,不斷調(diào)用MessageQueue的next方法,取出消息;
final Looper me = myLooper();
if (me == null) {
????throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
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;
????}
????msg.target.dispatchMessage(msg);
}
3、創(chuàng)建handler對象:創(chuàng)建handler對象時,會拿到當前線程的Loop對象,除了Main線程,其他線程都得初始化Loop對象,否則會報錯。通過Loop對象,把handler跟所屬線程的消息隊列關(guān)聯(lián)起來;
public Handler(Callback callback, boolean async) {
? ??mQueue = mLooper.mQueue;
}
4、發(fā)送消息:實際上是把消息加到消息隊列中,但在這一步之前,會把handler對象賦值給msg的target屬性;
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
????msg.target = this;
????if (mAsynchronous) {
????????msg.setAsynchronous(true);
????}
????return queue.enqueueMessage(msg, uptimeMillis);
}
5、接收消息:將消息加入到了消息隊列,通過Loop的輪詢,就能取出當前加入到消息隊列的消息。最終把消息分發(fā)給消息體的target屬性(調(diào)用了Handler的dispatchMessage方法),這個target實際上就是發(fā)出消息的handler對象;
public void dispatchMessage(Message msg) {
????if (msg.callback != null) {
????????handleCallback(msg);
????} else {
????????if (mCallback != null) {
????????????if (mCallback.handleMessage(msg)) {
????????????????return;
? ? ? ? ? ? }
????????}
????????handleMessage(msg);
????}
}
6、處理消息:最終來到了Handler的dispatchMessage方法,方法里會判斷callback對象是否為空,如果為空,就調(diào)用handleMessage方法,就是我們平時創(chuàng)建handler時重寫的handleMessage方法。
handleMessage(msg)