对于android内存泄漏问题,相信很多开发者都不会感到陌生,而在优化性能方面,内存泄漏,特别是在比较大的项目里面,由于多人协作开发,往往比较难定位到。
这里推荐一个开源工具,LeakCanary,来自square公司出品,可以帮助你实施监测内存泄漏问题。
那么,如何使用它呢?
下面让看下如何把它接入进去。
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 class MyApplication extends Application {
@Override public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
public class MyApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
MyApplication application = (MyApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
4.再在想观察的界面退出时,比如一个fragment,添加如下的代码:
public abstract class MyFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
5.你可以在logcat上面观察日志:
In com.kv.leakcanary:1.0:1 com.kv.leakcanary.MainActivity has leaked:
* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #1')
* references com.kv.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)
* leaks com.kv.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
更多更详细的功能可以参考以下链接。
本文参考的文章有:
https://www.jianshu.com/p/7db231163168
http://blog.youkuaiyun.com/yangzhaomuma/article/details/52008100