Android每日一問筆記-Handler簡述

基於每日一問的筆記,做一些整理,方便自己進行查看和記憶。
nanchen的文章


Handler 的簡單使用

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main3)
    // 請求網絡
    subThread.start()
}

override fun onDestroy() {
    subThread.interrupt()
    super.onDestroy()
}

private val handler by lazy(LazyThreadSafetyMode.NONE) { MyHandler() }
private val subThread by lazy(LazyThreadSafetyMode.NONE) { SubThread(handler) }

private class MyHandler : Handler() {
    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        // 主線程處理邏輯,一般這裏需要使用弱引用持有 Activity 實例,以免內存泄漏
    }
}

private class SubThread(val handler: Handler) : Thread() {
    override fun run() {
        super.run()
        // 耗時操作 比如做網絡請求

        // 網絡請求完畢,咱們就得嘩嘩譁通知 UI 刷新了,直接直接考慮 Handler 處理,其他方案暫時不做考慮
        // 第一種方法,一般這個 data 是請求結果解析的內容
        handler.obtainMessage(1,data).sendToTarget()
        // 第二種方法
        val message = Message.obtain() // 儘量使用 Message.obtain() 初始化
        message.what = 1
        message.obj = data // 一般這個 data 是請求結果解析的內容
        handler.sendMessage(message)
        // 第三種方法
        handler.post(object : Thread() {
            override fun run() {
                super.run()
                // 處理更新操作
            }
        })
    }
}
  • 上述代碼非常簡單,因爲網絡請求是一個耗時任務,所以我們新開了一個線程,並在網絡請求結束解析完畢後通過 Handler 來通知主線程去更新 UI,簡單採用了 3 種方式,細心的小夥伴可能會發現,其實第一種和第二種方法是一樣的。就是利用 Handler 來發送了一個攜帶了內容 Message 對象,值得一提的是:我們應該儘可能地使用 Message.obtain() 而不是 new Message() 進行 Message 的初始化,主要是 Message.obtain() 可以減少內存的申請
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;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
  • 代碼出現了一個 MessageQueue,並且最終調用了 MessageQueue#enqueueMessage方法進行消息的入隊

MessageQueue

  • MessageQueue 就是消息隊列,即存放多條消息 Message 的容器,它採用的是單向鏈表數據結構,而非隊列。它的 next() 指向鏈表的下一個 Message 元素。從入隊消息 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 {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            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;
}


Message next() {
    // ...
    int nextPollTimeoutMillis = 0;
    for (;;) {
        // ...
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }
            //...
        }
        //...
        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }
}
  • next() 方法其實很長,不過我們僅僅貼了極少的一部分,可以看到,裏面不過是有一個for (;;)的無限循環,循環體內部調用了一個 nativePollOnce(long, int) 方法。這是一個 Native 方法,實際作用是通過 Native 層的 MessageQueue 阻塞當前調用棧線程 nextPollTimeoutMillis 毫秒的時間。
  • 下面是 nextPollTimeoutMillis 取值的不同情況的阻塞表現:
    • 小於 0,一直阻塞,直到被喚醒;
    • 等於 0,不會阻塞;
    • 大於 0,最長阻塞 nextPollTimeoutMillis 毫秒,期間如被喚醒會立即返回。
  • 可以看到,最開始 nextPollTimeoutMillis 的初始化值是 0,所以不會阻塞,會直接去取 Message 對象,如果沒有取到 Message 對象數據,則直接會把 nextPollTimeoutMillis 置爲 -1,此時滿足小於 0 的條件,會被一直阻塞,直到其他地方調用另外一個 Native 方法 nativeWake(long) 進行喚醒。如果取到值的話,會直接把得到的 Message 對象進行返回。
  • nativeWake(long) 方法在前面的 MessageQueue#enqueueMessage 方法有個調用,調用時機是在 MessageQueue 入隊消息的過程中
  • Handler 發送了 Message,消息用MessageQueue進行存儲,使用MessageQueue#enqueueMessage 方法進行入隊,使用MessageQueue#next方法進行輪訓消息。這就不免拋出了一個問題,MessageQueue#next 方法是誰調用的?沒錯,就是 Looper。

Looper

  • Looper 在 Android 的消息機制中扮演着消息循環的角色,具體來說就是它會不停地從 MessageQueue 通過 next() 查看是否有新消息,如果有新消息就立刻處理,否則就任由 MessageQueue 阻塞在那裏。
public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    // ...

    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        //...
        try {
            // 分發消息給 handler 處理
            msg.target.dispatchMessage(msg);
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } finally {
            // ...
        }
        // ...
    }
}


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

private static void handleCallback(Message message) {
    message.callback.run();
}

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
  • 先會通過 myLooper() 方法得到 Looper 對象,如果這個 Looper 返回爲空的話,則直接拋出異常。否則進入到一個 for (;😉 循環中,調用 MessageQueue#next() 方法進行輪訓獲取 Message 對象,如果獲取的 Message 對象爲空,則直接退出 loop() 方法。否則直接通過 msg.target拿到 Handler 對象,並調用 Handler#dispatchMessage() 方法。
  • 如果 Message 設置了 callback 則,直接調用 message.callback.run(),否則判斷是否初始化了 mCallback

ThreadLocal

  • ThreadLocal 是用來存儲指定線程的數據的,當某些數據的作用域是該指定線程並且該數據需要貫穿該線程的所有執行過程時就可以使用 ThreadnLocal 存儲數據,當某線程使用 ThreadnLocal 存儲數據後,只有該線程可以讀取到存儲的數據,除此線程之外的其他線程是沒辦法讀取到該數據的。
  • 舉個栗子:
ThreadLocal<Boolean> local = new ThreadLocal<>();
// 設置初始值爲true.
local.set(true);

Boolean bool = local.get();
Logger.i("MainThread讀取的值爲:" + bool);

new Thread() {
    @Override
    public void run() {
        Boolean bool = local.get();
        Logger.i("SubThread讀取的值爲:" + bool);

        // 設置值爲false.
        local.set(false);
    }
}.start():

// 主線程睡1秒,確保上方子線程執行完畢再執行下面的代碼。
Thread.sleep(1000);

Boolean newBool = local.get();
Logger.i("MainThread讀取的新值爲:" + newBool);
  • 第一條 Log 無可置疑,因爲設置了值爲 true,因爲打印結果沒什麼好說的。對於第二條 Log,根據上方介紹,某線程使用 ThreadLocal 存儲的數據,只能被該線程讀取,因此第二條 Log 的結果是:null。緊接着在子線程中設置了 ThreadLocal 的值爲 false,然後第三條 Log 將被打印,原理同上,子線程中設置了 ThreadLocal 的值並不影響主線程的數據,所以打印是 true。
  • 實驗結果證實:就算是同一個 ThreadLocal 對象,任一線程對其的 set() 和 get() 方法的操作都是相互獨立互不影響的。

Looper.myLooper()

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));
}
  • 這就是在子線程中使用 Handler 前,必須要調用 Looper.prepare() 的原因。
  • 可能你會疑問,我在主線程使用的時候,沒有要求 Looper.prepare() 呀。
    原來,我們在 ActivityThread 中,有去顯示調用 Looper.prepareMainLooper():
public static void main(String[] args) {
        // ...
        Looper.prepareMainLooper();
        // ...
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        //...
        Looper.loop();
        // ...
    }
  • 我們看看 Looper.prepareMainLooper():
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章