標籤:
開始使用
在 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); }}
如何使用
使用 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); }}
工作機制
-
RefWatcher.watch() 建立一個 KeyedWeakReference 到要被監控的對象。
-
然後在後台線程檢查引用是否被清除,如果沒有,調用GC。
-
如果引用還是未被清除,把 heap 記憶體 dump 到 APP 對應的檔案系統中的一個 .hprof 檔案中。
-
在另外一個進程中的 HeapAnalyzerService 有一個 HeapAnalyzer 使用HAHA 解析這個檔案。
-
得益於唯一的 reference key, HeapAnalyzer 找到 KeyedWeakReference,定位記憶體泄露。
-
HeapAnalyzer 計算 到 GC roots 的最短強引用路徑,並確定是否是泄露。如果是的話,建立導致泄露的引用鏈。
-
引用鏈傳遞到 APP 進程中的 DisplayLeakService, 並以通知的形式展示出來。
LeakCanary Android 和 Java 記憶體泄露檢測。