天天看點

LeakCanary簡單介紹

LeakCanary

Github 位址:https://github.com/square/leakcanary

內建方案:

在 moduleName(不是Project)/build.gradle中的

dependencies {

}

方法内添加代碼

debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.5.1’

releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.5.1’

testCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.5.1’

在目前自定義Application extends Application 中的 onCreate()方法中添加

if (LeakCanary.isInAnalyzerProcess(this)) {

// This process is dedicated to LeakCanary for heap analysis.

// You should not init your app in this process.

return;

}

LeakCanary.install(this);

重新build 應用。讓程式跑一會。

LeakCanary 執行個體分析

下邊是我自己造的一個大的記憶體洩露

直接上圖

LeakCanary簡單介紹

我自Activity-A 中造了一個記憶體洩露,

finish 後的Activity 在 接近一分鐘的時間gc沒有回收它。

LeakCanary 在手機上顯示的圖如下圖所示:

LeakCanary簡單介紹

它說MainApplication 中 static 參數 activityList 持有已finish 掉的Activity-A 的對象造成47M記憶體洩露(在标題欄上沒有顯示全部)

然後就開始根據這個資訊去改進。現在不讓MainApplication 中activityList 不持有 Activity-A的對象。看記憶體變化的圖檔

下圖所示:

LeakCanary簡單介紹

很明顯從原來的80+M的記憶體占有量降到40+M的記憶體占有量。

以上就是使用 LeakCanary 工具分析并解決記憶體的一個簡單的示例。希望對大家有所幫助