Handler學習筆記

Handler相關知識梳理

1、爲什麼要使用Handler?

因爲Android系統只能在主線更新UI,而我們的數據操作經常是由子線程來完成的。爲什麼子線程不能更新UI?因爲如果多線程操作UI會導致UI處於不可預知的狀態;那可不可以用加鎖的方式來解決這個問題呢?加鎖會讓訪問UI的邏輯變得很複雜,而且會降低訪問效率。

2、Handler消息機制原理

在程序中,我們一般的做法是調用Handler.SendMessage等方法來發送消息,最終會調用Handler.SendMessageAtTime方法將消息插入到消息隊列MessageQueue中

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;//消息隊列,以單鏈表的形式保存
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;//此處的target即爲Handler
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

在MessageQueue.enqueueMessage方法中,會根據消息要發送的時間來插入

boolean enqueueMessage(Message msg, long when) {
    synchronized (this) {
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

Looper是消息機制中非常重要的一個東西,主線程會調用Looper.loop方法一直輪詢,發現有消息就將消息轉發給Handler
那麼主線程的Looper是怎麼創建的呢?
在應用程序啓動的過程中,會創建一個主線程,ActivityThread,看它的main方法(應用程序的真正入口)

public static void More ...main(String[] args) {    //只貼了相關的代碼

    Looper.prepareMainLooper();//爲主線程創建了Looper
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
            sMainThreadHandler =thread.getHandler();//主線程的Handler
    }
    Looper.loop();//進入消息循環

}

重點來看Looper.loop()方法:

public static void loop() {
    final Looper me = myLooper();//調用了sThreadLocal.get()來獲取當前線程的looper,ThreadLocal以UI線程爲KEY,以Looper爲值這樣就把一個線程和一個looper關聯起來了
    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;
        }

        // This must be in a local variable, in case a UI event sets the logger
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(msg);//此處即通過Message中保存的Handler對象來發送消息

        ```
    }
}

再回到Handler的dispatchMessage:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}
public void handleMessage(Message msg) {
}

可以看到,最終調用的handleMessage方法是一個空方法,也就是我們在new一個handler時重寫的方法

我們再來看看Looper的構造方法:

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

可以看到,在Looper的構造方法中,new了一個消息隊列

而在我們的Handler的構造方法中:

public Handler(Callback callback, boolean async) {

    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

所以,通過Handler發送的消息,插入的消息隊列是Looper new出來的

3、圖解

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章