2015年5月11日 星期一

leakcanary

今天看到有人在討論的工具 library

leakcanary

如他的名字, 他是拿來試毒氣的金絲雀
主要是把 MAT (Memory Analyzer) 做進去 application level

Getting Started

dependencies {  
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'  
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'  
}  

PS. 我的 build.gradle 一直少加了

repositories {  
    mavenCentral()  
}  

結果 dependencies 一直出問題
加了後,他會自己去抓 library 了

public class ExampleApplication extends Application {  
  @Override public void onCreate() {  
       super.onCreate();  
       LeakCanary.install(this);  
  }  
}  

到此為止, 他做了什麼

他埋了一個 Activity Watch 在 Application level
所以當你的 Activity finish() 了, 一但 Activity 沒有被正確回收
他就在背景做 heap dump
利用 Eclipse 的 MAT(Memory Analyzer) 去分析是誰 block 住
activity 這個 reference 是誰造成 memory leak

然後他會在 notification dump 出 memory leak 的結果
拉下來點開就有一個分析的畫面跟你說哪邊 memory leak

然後要怎用

可以隨時利用他

refWatcher = LeakCanary.install(this);

寫個 getter 把 refWatcher export 出來

RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());

然後監控你要的變數

refWatcher.watch(schrodingerCat);

薛丁格的貓 被 clear 掉,卻沒有正常被 gc 掉的話
就會觸發 notification

另外因為 heap dump 需要幾秒鐘
所以會等一下才跑出來