原文鏈接(http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/)
LeakCanary
Android 和 Java 內(nèi)存泄露檢測。
“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中:
publicclassExampleApplicationextendsApplication{@OverridepublicvoidonCreate(){super.onCreate();LeakCanary.install(this);}}
這樣,就萬事俱備了!在 debug build 中,如果檢測到某個 activity 有內(nèi)存泄露,LeakCanary 就是自動地顯示一個通知。
為什么需要使用 LeakCanary?
問得好,看這個文章LeakCanary: 讓內(nèi)存泄露無所遁形
如何使用
使用RefWatcher監(jiān)控那些本該被回收的對象。
RefWatcherrefWatcher={...};// 監(jiān)控refWatcher.watch(schrodingerCat);
LeakCanary.install()會返回一個預定義的RefWatcher,同時也會啟用一個ActivityRefWatcher,用于自動監(jiān)控調(diào)用Activity.onDestroy()之后泄露的 activity。
publicclassExampleApplicationextendsApplication{publicstaticRefWatchergetRefWatcher(Contextcontext){ExampleApplicationapplication=(ExampleApplication)context.getApplicationContext();returnapplication.refWatcher;}privateRefWatcherrefWatcher;@OverridepublicvoidonCreate(){super.onCreate();refWatcher=LeakCanary.install(this);}}
使用RefWatcher監(jiān)控 Fragment:
publicabstractclassBaseFragmentextendsFragment{@OverridepublicvoidonDestroy(){super.onDestroy();RefWatcherrefWatcher=ExampleApplication.getRefWatcher(getActivity());refWatcher.watch(this);}}
工作機制
RefWatcher.watch()創(chuàng)建一個KeyedWeakReference到要被監(jiān)控的對象。
然后在后臺線程檢查引用是否被清除,如果沒有,調(diào)用GC。
如果引用還是未被清除,把 heap 內(nèi)存 dump 到 APP 對應的文件系統(tǒng)中的一個.hprof文件中。
在另外一個進程中的HeapAnalyzerService有一個HeapAnalyzer使用HAHA解析這個文件。
得益于唯一的 reference key,HeapAnalyzer找到KeyedWeakReference,定位內(nèi)存泄露。
HeapAnalyzer計算到 GC roots 的最短強引用路徑,并確定是否是泄露。如果是的話,建立導致泄露的引用鏈。
引用鏈傳遞到 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. (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 導致的內(nèi)存泄露
隨著時間的推移,很多SDK 和廠商 ROM 中的內(nèi)存泄露問題已經(jīng)被盡快修復了。但是,當這樣的問題發(fā)生時,一般的開發(fā)者能做的事情很有限。
LeakCanary 有一個已知問題的忽略列表,AndroidExcludedRefs.java,如果你發(fā)現(xiàn)了一個新的問題,請?zhí)嵋粋€ issue并附上 leak trace, reference key, 機器型號和 SDK 版本。如果可以附帶上 dump 文件的 鏈接那就再好不過了。
對于最新發(fā)布的 Android,這點尤其重要。你有機會在幫助在早期發(fā)現(xiàn)新的內(nèi)存泄露,這對整個 Android 社區(qū)都有極大的益處。
開發(fā)版本的 Snapshots 包在這里:Sonatype'ssnapshotsrepository。
leak trace 之外
有時,leak trace 不夠,你需要通過MAT或者YourKit深挖 dump 文件。
通過以下方法,你能找到問題所在:
查找所有的com.squareup.leakcanary.KeyedWeakReference實例。
檢查key字段
Find theKeyedWeakReferencethat has akeyfield equal to the reference key reported by LeakCanary.
找到 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
MyLeaks
保存 leak trace
DisplayLeakActivitysaves up to 7 heap dumps & leak traces in the app directory. You can change that number by providingR.integer.__leak_canary_max_stored_leaksin your app:
在 APP 的目錄中,DisplayLeakActivity保存了 7 個 dump 文件和 leak trace。你可以在你的 APP 中,定義R.integer.__leak_canary_max_stored_leaks來覆蓋類庫的默認值。
20
上傳 leak trace 到服務器
你可以改變處理完成的默認行為,將 leak trace 和 heap dump 上傳到你的服務器以便統(tǒng)計分析。
創(chuàng)建一個LeakUploadService, 最簡單的就是繼承DisplayLeakService:
publicclassLeakUploadServiceextendsDisplayLeakService{@OverrideprotectedvoidafterDefaultHandling(HeapDumpheapDump,AnalysisResultresult,StringleakInfo){if(!result.leakFound||result.excludedLeak){return;}myServer.uploadLeakBlocking(heapDump.heapDumpFile,leakInfo);}}
請確認 release 版本 使用RefWatcher.DISABLED:
publicclassExampleApplicationextendsApplication{publicstaticRefWatchergetRefWatcher(Contextcontext){ExampleApplicationapplication=(ExampleApplication)context.getApplicationContext();returnapplication.refWatcher;}privateRefWatcherrefWatcher;@OverridepublicvoidonCreate(){super.onCreate();refWatcher=installLeakCanary();}protectedRefWatcherinstallLeakCanary(){returnRefWatcher.DISABLED;}}
自定義RefWatcher:
publicclassDebugExampleApplicationextendsExampleApplication{protectedRefWatcherinstallLeakCanary(){returnLeakCanary.install(app,LeakUploadService.class);}}
別忘了注冊 service:
demo
一個非常簡單的 LeakCanary demo:https://github.com/liaohuqiu/leakcanary-demo