http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/
LeakCanary 中文使用說明
10 May 2015
LeakCanary
Android 和 Java 記憶體洩露檢測。
“A small leak will sink a great ship.” - Benjamin Franklin
千裡之堤, 毀于蟻穴。 -- 《韓非子·喻老》

demo
一個非常簡單的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo
開始使用
在
build.gradle
中加入引用,不同的編譯使用不同的引用:
dependencies {
debugCompile \'com.squareup.leakcanary:leakcanary-android:1.3\'
releaseCompile \'com.squareup.leakcanary:leakcanary-android-no-op:1.3\'
}
在
Application
中:
public class ExampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
這樣,就萬事俱備了! 在 debug build 中,如果檢測到某個 activity 有記憶體洩露,LeakCanary 就是自動地顯示一個通知。
為什麼需要使用 LeakCanary?
問得好,看這個文章LeakCanary: 讓記憶體洩露無所遁形
如何使用
使用
RefWatcher
監控那些本該被回收的對象。
RefWatcher refWatcher = {...};
// 監控
refWatcher.watch(schrodingerCat);
LeakCanary.install()
會傳回一個預定義的
RefWatcher
,同時也會啟用一個
ActivityRefWatcher
,用于自動監控調用
Activity.onDestroy()
之後洩露的 activity。
public class ExampleApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
使用
RefWatcher
監控 Fragment:
public abstract class BaseFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
工作機制
-
建立一個 KeyedWeakReference 到要被監控的對象。RefWatcher.watch()
- 然後在背景線程檢查引用是否被清除,如果沒有,調用GC。
- 如果引用還是未被清除,把 heap 記憶體 dump 到 APP 對應的檔案系統中的一個
檔案中。.hprof
- 在另外一個程序中的
有一個HeapAnalyzerService
使用HAHA 解析這個檔案。HeapAnalyzer
- 得益于唯一的 reference key,
找到HeapAnalyzer
,定位記憶體洩露。KeyedWeakReference
-
計算 到 GC roots 的最短強引用路徑,并确定是否是洩露。如果是的話,建立導緻洩露的引用鍊。HeapAnalyzer
- 引用鍊傳遞到 APP 程序中的
, 并以通知的形式展示出來。DisplayLeakService
如何複制 leak trace?
在 Logcat 中,你可以看到類似這樣的 leak trace:
In com.example.leakcanary:1.0:1 com.example.leakcanary.MainActivity has leaked:
* GC ROOT thread java.lang.Thread.<Java Local> (named \'AsyncTask #1\')
* references com.example.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)
* leaks com.example.leakcanary.MainActivity instance
* Reference Key: e71f3bf5-d786-4145-8539-584afaecad1d
* Device: Genymotion generic Google Nexus 6 - 5.1.0 - API 22 - 1440x2560 vbox86p
* Android Version: 5.1 API: 22
* Durations: watch=5086ms, gc=110ms, heap dump=435ms, analysis=2086ms
你甚至可以通過分享按鈕把這些東西分享出去。
SDK 導緻的記憶體洩露
随着時間的推移,很多SDK 和廠商 ROM 中的記憶體洩露問題已經被盡快修複了。但是,當這樣的問題發生時,一般的開發者能做的事情很有限。
LeakCanary 有一個已知問題的忽略清單,AndroidExcludedRefs.java,如果你發現了一個新的問題,請提一個 issue 并附上 leak trace, reference key, 機器型号和 SDK 版本。如果可以附帶上 dump 檔案的 連結那就再好不過了。
對于最新釋出的 Android,這點尤其重要。你有機會在幫助在早期發現新的記憶體洩露,這對整個 Android 社群都有極大的益處。
開發版本的 Snapshots 包在這裡: Sonatype\'s
snapshots
repository。
leak trace 之外
有時,leak trace 不夠,你需要通過 MAT 或者 YourKit 深挖 dump 檔案。
通過以下方法,你能找到問題所在:
- 查找所有的
執行個體。com.squareup.leakcanary.KeyedWeakReference
- 檢查
字段key
- Find the
that has aKeyedWeakReference
field equal to the reference key reported by LeakCanary.key
- 找到 key 和 和 logcat 輸出的 key 值一樣的
。KeyedWeakReference
-
字段對應的就是洩露的對象。referent
- 剩下的,就是動手修複了。最好是檢查到 GC root 的最短強引用路徑開始。
自定義
UI 樣式
DisplayLeakActivity
有一個預設的圖示和标簽,你隻要在你自己的 APP 資源中,替換以下資源就可。
res/
drawable-hdpi/
__leak_canary_icon.png
drawable-mdpi/
__leak_canary_icon.png
drawable-xhdpi/
__leak_canary_icon.png
drawable-xxhdpi/
__leak_canary_icon.png
drawable-xxxhdpi/
__leak_canary_icon.png
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="__leak_canary_display_activity_label">MyLeaks</string>
</resources>
儲存 leak trace
DisplayLeakActivity
saves up to 7 heap dumps & leak traces in the app directory. You can change that number by providing
R.integer.__leak_canary_max_stored_leaks
in your app:
在 APP 的目錄中,
DisplayLeakActivity
儲存了 7 個 dump 檔案和 leak trace。你可以在你的 APP 中,定義
R.integer.__leak_canary_max_stored_leaks
來覆寫類庫的預設值。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="__leak_canary_max_stored_leaks">20</integer>
</resources>
上傳 leak trace 到伺服器
你可以改變處理完成的預設行為,将 leak trace 和 heap dump 上傳到你的伺服器以便統計分析。
建立一個
LeakUploadService
, 最簡單的就是繼承
DisplayLeakService
:
public class LeakUploadService extends DisplayLeakService {
@Override
protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
myServer.uploadLeakBlocking(heapDump.heapDumpFile, leakInfo);
}
}
請确認 release 版本 使用
RefWatcher.DISABLED
:
public class ExampleApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = installLeakCanary();
}
protected RefWatcher installLeakCanary() {
return RefWatcher.DISABLED;
}
}
自定義
RefWatcher
:
public class DebugExampleApplication extends ExampleApplication {
protected RefWatcher installLeakCanary() {
return LeakCanary.install(app, LeakUploadService.class);
}
}
别忘了注冊 service:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
>
<application android:name="com.example.DebugExampleApplication">
<service android:name="com.example.LeakUploadService" />
</application>
</manifest>
demo
一個非常簡單的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo