ADB dumpheap + MAT 分析內(nèi)存泄漏

廢話不多說直接說流程

  1. 通過adb dump 內(nèi)存快照
adb shell am dumpheap {進(jìn)程名} {存儲路徑} 

例如:
adb shell am dumpheap nova.priv.terminal.player.PlayService /sdcard/1.hprof
  1. 導(dǎo)出到電腦上
adb pull /sdcard/1.hprof C:\Users\...\1.hprof
  • 導(dǎo)出以后我們會得到1.hprof文件,但是這個不是mat工具用到的標(biāo)準(zhǔn)文件。我們需要使用sdk自帶的hprof-conv.exe(platform-tools文件夾下) 工具進(jìn)行轉(zhuǎn)換,轉(zhuǎn)換以后我們就得到了1_mat.hprof文件
轉(zhuǎn)換mat標(biāo)準(zhǔn)文件
命令:hprof-conv -z src dst
例如:hprof-conv -z 1.hprof 1_mat.hprof
image.png
  • 進(jìn)入Histogram 頁面有我們在紅框位置輸入我們想要找的類,然后右鍵選擇merge shortest paths to Gc roots然后在選擇exclude all phantom/weak/soft etc.references選項(xiàng)

    image.png

  • 就得到了如下的引用圖,從圖中我們分析出 loginActivity是被inputMethodManager所引用(這其實(shí)是android系統(tǒng)的一個bug),所以我們主要將兩者之間的聯(lián)系給斷開就行,解決方法如下


    image.png
  • 使用反射的方式將引用的view置為null

        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        try {
            //獲得 所有屬性  getField->public  以及父類
            Field mCurRootViewField = InputMethodManager.class.getDeclaredField("mCurRootView");
            //設(shè)置允許訪問權(quán)限
            mCurRootViewField.setAccessible(true);
            // 對象
            Object mCurRootView = mCurRootViewField.get(im);
            if (null != mCurRootView){
                Context context = ((View) mCurRootView).getContext();
                if (context == this){
                    //破怪gc 引用鏈
                    mCurRootViewField.set(im,null);
            }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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