Handler 源碼從零學(xué)習(xí)筆記 (二)

/*
 * Set this flag to true to detect anonymous, local or member classes
 * that extend this Handler class and that are not static. These kind
 * of classes can potentially create leaks.

 * 將此標(biāo)志設(shè)置為true以檢測(cè)此 Handler 類(lèi)不是靜態(tài)的匿名,本地或成員類(lèi)。這些類(lèi)
 * 可能會(huì)產(chǎn)生泄漏。
 */
private static final boolean FIND_POTENTIAL_LEAKS = false;

  /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.

     * 你可以在你實(shí)例化一個(gè) Handler 的時(shí)候使用 Callback 接口(就是我們說(shuō)的回調(diào)接口)
     * 避免必須實(shí)現(xiàn)一個(gè) Handler 的子類(lèi)。
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

  /**
     * Subclasses must implement this to receive messages.
     * 子類(lèi)必須實(shí)現(xiàn)這個(gè)方法來(lái)接受 Message 對(duì)象
     */
    public void handleMessage(Message msg) {
    }

  /**
     * Handle system messages here.
     * 該方法用于處理系統(tǒng)的 Message
     */
    public void dispatchMessage(Message msg) {
        // 如果傳入的 Message 的回調(diào)函數(shù)不為空
        if (msg.callback != null) {
        // 調(diào)用 handleCallback 方法
            handleCallback(msg);
        } else { // 不為空
            if (mCallback != null) { // 如果 Handler 的 Callback 不為空
                if (mCallback.handleMessage(msg)) { // 返回值為 true 調(diào)用 return
                    return;
                }
            }
            handleMessage(msg);// 調(diào)用 handleMessage() 上面有介紹
        }
    }

   /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.

     * 默認(rèn)的構(gòu)造函數(shù),通過(guò)當(dāng)前線程的 Lopper 對(duì)象關(guān)聯(lián)當(dāng)前 Handler。
     * 如果這個(gè)線程沒(méi)有 Lopper,那么該 Handler 將無(wú)法接受 Message,因此會(huì)拋出一個(gè)異常。
     */
    public Handler() {
        this(null, false);
    }

  /**
     * Constructor associates this handler with the {@link Looper} for the
     * current thread and takes a callback interface in which you can handle
     * messages.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     *
     * @param callback The callback interface in which to handle messages, or null.
     *                              處理 Message 的回調(diào)接口,或者傳 null

     * 相對(duì)于默認(rèn)構(gòu)造函數(shù),添加了一個(gè) Callback 參數(shù),表示會(huì)通過(guò)該 Callback 對(duì)象處理 Message
     */
    public Handler(Callback callback) {
        this(callback, false);
    }

/**
     * Use the provided {@link Looper} instead of the default one.
     *
     * @param looper The looper, must not be null.
     *                           Looper 對(duì)象,不能傳入 null
     * 使用傳入的 Looper 代替默認(rèn)的 Looper
     */
    public Handler(Looper looper) {
        this(looper, null, false);
    }

  /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.

     * 使用傳入的 Looper 代替默認(rèn)的,并且傳入 Callback 用于處理 Message
     */
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

/**
     * Use the {@link Looper} for the current thread
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide

     * 使用當(dāng)前線程默認(rèn)的 Looper 并且設(shè)置該 Handler 是否需要是異步的。
     * Handler 是默認(rèn)同步的,除非你調(diào)用該構(gòu)造函數(shù)設(shè)置表示使用異步。
     * 異步消息相對(duì)于同步消息,不需要對(duì)消息進(jìn)行同步排序,并且不受 MessageQueue 的 enqueueSyncBarrier(long) 所帶來(lái)的同步障礙影響。
     */
    public Handler(boolean async) {
        this(null, async);
    }

前面所有的構(gòu)造函數(shù)本質(zhì)上都是調(diào)用了下面兩個(gè)構(gòu)造函數(shù),我們來(lái)看看構(gòu)造函數(shù)到底做了什么?

/**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.

     * 使用當(dāng)前默認(rèn) Looper 和傳入的 Callback ,傳入 boolean 來(lái)設(shè)置該 Handler 是否需要是異步的。
     * @hide
     */
    public Handler(Callback callback, boolean async) {
        // 如果有內(nèi)存泄漏危險(xiǎn)
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                // 打印警告 log"該 Handler 應(yīng)該為 static ,否則可能會(huì)導(dǎo)致內(nèi)存泄漏"
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        // 獲取 Looper
        mLooper = Looper.myLooper();
        if (mLooper == null) { // 獲取到為 null 拋出異常 “無(wú)法在線程內(nèi)部創(chuàng)建沒(méi)有調(diào)用 
                                          // Looper.prepare() 方法的 handler”
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        // 從 Looper 獲取 MessageQueue
        mQueue = mLooper.mQueue;
        // mCallback賦值
        mCallback = callback;
        // mAsynchronous 賦值
        mAsynchronous = async;
    }

/**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.  Also set whether the handler
     * should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide

     * 添加了 Looper 參數(shù)指定 Looper,其余跟上一個(gè)一樣。
     */
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

下面是各個(gè)方法的解讀

  • getMessageName(Message message):
    該方法返回一個(gè) Message 的指定名稱(chēng)(大概就是說(shuō)返回一個(gè)唯一標(biāo)識(shí))。默認(rèn)返回Message 的 Callback 的類(lèi)名,如果 message.callback 為空,返回 Message.what 的十六進(jìn)制數(shù)。

  • obtainMessage():
    該方法從全局的 Message Pool(消息池)返回一個(gè) Message 對(duì)象。這樣的效率比重新創(chuàng)建一個(gè)實(shí)例要高。并設(shè)置 Message.target == this。如果你不想用這種方法,可以直接調(diào)用 Message.obtain()。

  • obtainMessage(int what):
    和 obtainMessage() 一樣,但是給返回的 Message 對(duì)象設(shè)置了 what 。

  • obtainMessage(int what, Object obj):
    obtainMessage(int what, int arg1, int arg2):
    obtainMessage(int what, int arg1, int arg2, Object obj):
    與 obtainMessage() 相同,但是設(shè)置了 whta 和 obj 兩個(gè)屬性。

  • public final boolean post(Runnable r):
    添加 Runnable 對(duì)象到 MessageQueue 中。該 Runnable 對(duì)象將會(huì)在該 Handler bain綁定到的 Thread 上運(yùn)行。

  • public final boolean postAtTime(Runnable r, long uptimeMillis):
    添加 Runnable 對(duì)象到 MessageQueue 中。該 Runnable 對(duì)象將會(huì)在給定的時(shí)間點(diǎn)運(yùn)行。返回:true 表示該 Runnable 成功添加到 MessageQueue 中,否則返回 false,通常是因?yàn)?Looper 處理 MessageQueue 正在退出。注意,返回 true 并不意味著該 Runnable 一定會(huì)被執(zhí)行 -- 如果 Looper 在 Message 送達(dá)時(shí)間之前 quit,那么 Message 將會(huì)丟失。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容