1. 用法:?
1)在build.gradle中加入引用,不同的編譯使用不同的引用:
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
2)在Application中:
public classExampleApplicationextendsApplication {
privateRefWatchermRefWatcher;
public staticRefWatchergetRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
returnapplication.mRefWatcher;
}
@Override
public voidonCreate() {
super.onCreate();
mRefWatcher= LeakCanary.install(this);
}
}
3)在Activity中LeakCanary 會自動監測泄露情況
4)在Fragment中的onDestroy方法中調用:
RefWatcher refWatcher = ExampleApplication.getRefWatcher(this);
refWatcher.watch(this);
5)監控其他泄漏
RefWatcher refWatcher = MyApplication.refWatcher;
refWatcher.watch(someObjNeedGced);
6)如果有泄漏則輸出:
01-06 14:11:35.255 2628-3247/demo.leakcanary.srain.in.leakcanarydemo D/LeakCanary: In demo.leakcanary.srain.in.leakcanarydemo:1.0:1.
* demo.leakcanary.srain.in.leakcanarydemo.TestActivity has leaked:
* GC ROOT static demo.leakcanary.srain.in.leakcanarydemo.TestDataModel.sInstance
* references demo.leakcanary.srain.in.leakcanarydemo.TestDataModel.mRetainedTextView
* references android.widget.TextView.mContext
* leaks demo.leakcanary.srain.in.leakcanarydemo.TestActivity instance
* Reference Key: 8e73e5d3-f2b7-42bf-8b65-54aba952525a
* Device: ZTE ZTE ZTE STAR P898S10
* Android Version: 4.4.2 API: 19
* Durations: watch=5076ms, gc=151ms, heap dump=312ms, analysis=10109ms
根據輸出的泄露項進行優化,
2.總結:
我對LeakCanary的使用還處于初級階段,在以后的編程中,會盡量使用這個工具進行優化,將會有更加復雜的應用環境,對于這個工具理解的不足,也會在以后的使用中進行改進.