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的使用还处于初级阶段,在以后的编程中,会尽量使用这个工具进行优化,将会有更加复杂的应用环境,对于这个工具理解的不足,也会在以后的使用中进行改进.
网友评论