Android 復(fù)習(xí)handler-線程,handler,message的關(guān)系

前言

本文只是為了復(fù)習(xí)handler,需要提前了解查看handler源碼

記錄的問(wèn)題

1線程和handler有沒(méi)有關(guān)系?message存在哪里?
2handler在activity中的內(nèi)存泄漏怎么發(fā)生的?什么解決方案

線程和handler有沒(méi)有關(guān)系?message存在哪里?

答案是有!message存在Looper的messageQueue里
那線程和handler關(guān)系是什么?
答案是Looper,首先我們看handler的幾個(gè)構(gòu)造函數(shù)

    @Deprecated
    public Handler() {
        this(null, false);
    }
    @Deprecated
    public Handler(@Nullable Callback callback) {
        this(callback, false);
    }
    public Handler(@NonNull Looper looper) {
        this(looper, null, false);
    }
    public Handler(@NonNull Looper looper, @Nullable Callback callback) {
        this(looper, callback, false);
    }
    @UnsupportedAppUsage
    public Handler(boolean async) {
        this(null, async);
    }
    public Handler(@Nullable Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    @UnsupportedAppUsage
    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

可以看到最終賦值的就四個(gè)變量,mLooper,mQueue,mCallback,mAsynchronous,其中mQueue是looper里的,從構(gòu)造函數(shù)看出,主要?jiǎng)?chuàng)建handler的方式由兩種
1傳入Looper
2從Looper.myLooper();中獲取
第一種稍后去研究,我們使用handler主要是通過(guò)第二種方式,所以需要查看Looper.myLooper()里干了什么

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

發(fā)現(xiàn)這個(gè)Looper是在ThreadLocal中存儲(chǔ)的,那ThreadLocal什么時(shí)候存入的Looper?AS功能很強(qiáng)大,搜就好了


    /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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");
        }
        //這里設(shè)置了
        sThreadLocal.set(new Looper(quitAllowed));
    }

    /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. See also: {@link #prepare()}
     *
     * @deprecated The main looper for your application is created by the Android environment,
     *   so you should never need to call this function yourself.
     */
    @Deprecated
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

發(fā)現(xiàn)在prepare的時(shí)候會(huì)設(shè)置Looper,這個(gè)方法只提供給prepare()和prepareMainLooper()使用了,通過(guò)注解可以發(fā)現(xiàn)prepareMainLooper()已經(jīng)執(zhí)行了,所以主線程中我們可以默認(rèn)理解已經(jīng)執(zhí)行過(guò)了,詳細(xì)可以參考activity啟動(dòng)流程
quitAllowed這個(gè)參數(shù)主要是判斷是否可以執(zhí)行messageQueue是否可以執(zhí)行quit用的,這里不展開(kāi)討論
最終我們發(fā)現(xiàn),sThreadLocal里的Looper只有兩種情況可以存在
ThreadLocal這個(gè)東西主要是為了保證當(dāng)前線程中緩存的Looper只存在一個(gè)
那么通過(guò)以上代碼我們確定了Thread
1主動(dòng)調(diào)用prepare
2UI線程啟動(dòng)時(shí)直接通過(guò)prepareMainLooper創(chuàng)建

通過(guò)以上代碼我們了解了創(chuàng)建handler時(shí),需要觀測(cè)Looper是在哪個(gè)線程創(chuàng)建的,創(chuàng)建的Looper里持有著messageQueue負(fù)責(zé)壓入消息
那么我們需要反思幾個(gè)問(wèn)題
1如果我們自己在主線程創(chuàng)建的Looper是否是同一個(gè)MessageQueue?
首先這個(gè)問(wèn)題本身就是不成立的,在ActivityThread創(chuàng)建時(shí),當(dāng)前線程的ThreadLocal已經(jīng)持有了初始化時(shí)創(chuàng)建的Looper,所以不可能在主線程創(chuàng)建Looper的
2上面的問(wèn)題,如果通過(guò)反射,重新設(shè)置ThreadLocal呢?
通過(guò)反射的方法是可以替換Looper的,但是我們替換的Looper必須還要通知ActivityThread,這和重啟一個(gè)Activity的成本一樣了
我簡(jiǎn)單做了個(gè)試驗(yàn)

 var f = Looper::class.java.getDeclaredField("sThreadLocal")
 var m = Looper::class.java.getDeclaredField("sMainLooper")
 m.setAccessible(true);
 f.setAccessible(true);
 var t=ThreadLocal<Looper>();
   f.set(Looper.myLooper(),t)
 m.set(Looper.myLooper(),null)
 t.set(null);
 Looper.prepareMainLooper();
   Handler(Looper)
 h = Handler();

大體思路是把當(dāng)前的Looper里的sThreadLocal和sMainLooper全部替換,通過(guò)prepareMainLooper重新創(chuàng)建Looper,前面幾步都沒(méi)什么問(wèn)題,甚至創(chuàng)建的Handler里的MessageQueue也替換了
debug如下圖
修改前創(chuàng)建handler的messageQueue


修改前的messageQueue

修改后創(chuàng)建handler的messageQueue


修改后創(chuàng)建handler的messageQueue

可以看到Looper和MessageQueue全部替換成功了,但是當(dāng)執(zhí)行UI操作的時(shí)候,會(huì)爆出類似如下的異常
異常

為什么呢?
因?yàn)锳ctivityThread創(chuàng)建時(shí),通過(guò)mainThread獲取了一個(gè)Handler,這個(gè)Handler持有的Looper就是被我們替換掉的Looper,當(dāng)UI更新的時(shí)候,發(fā)現(xiàn)當(dāng)前的mainLooper和mainThread持有的Looper不一致,各種層層嵌套,拋出這個(gè)異常。

handler在activity中的內(nèi)存泄漏怎么發(fā)生的

上面的分析我們知道handler持有的Looper是主線程里的Looper,我們創(chuàng)建Handler大多會(huì)通過(guò)內(nèi)部類創(chuàng)建,內(nèi)部類的實(shí)例會(huì)隱性持有當(dāng)前類(Activity)的實(shí)例,這樣就讓Handler間接強(qiáng)持有了當(dāng)前類的實(shí)例,而handler的生命周期是跟主線程Looper里的MessageQueue里的Message里的target保持一致的,因?yàn)樘幚鞰essage時(shí)會(huì)通過(guò)Message里的target去獲取handler,所以會(huì)造成handler生命周期可能會(huì)比Activity長(zhǎng),當(dāng)Activity需要銷(xiāo)毀時(shí),因?yàn)镠andler持有的Activity沒(méi)有釋放,造成內(nèi)存泄露。
怎么解決呢?
1,持有的Handler在activity銷(xiāo)毀前,將Message全部銷(xiāo)毀,去除內(nèi)部類的持有,handler銷(xiāo)毀,讓Handler的生命周期小于Activity(removeCallbacksAndMessages方法)
2,將Handler通過(guò)弱引用Activity創(chuàng)建(WeakReference<Activity>)
以上就是Handler的復(fù)習(xí)

?著作權(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)容