关于Android项目的内存泄漏是一个老生常谈的问题,之前一直是在写代码时各种注意,比如IO流要及时关闭,引用的curcor要及时关闭等,这样做确实能规避一部分的内存泄漏,不过还是会有漏网之鱼,因此除了养成良好的编程习惯之外,还需要引用各种框架来主动检测,对于框架,本人习惯使用leakcanary。需要注意的一点是,leakcanary可以检测Activity和fragment中的内存泄漏,网上有些文章中并没有写全而是只写了Activity的。下面是本人总结的引用leakcanary的步骤:
1:在项目的build.gradle中加入依赖:
debugCompile'com.squareup.leakcanary:leakcanary-android:1.5+'
releaseCompile'com.squareup.leakcanary:leakcanary-android-no-op:1.5+'
testCompile'com.squareup.leakcanary:leakcanary-android-no-op:1.5+'
debugCompile'com.squareup.haha:haha:2.0.3'
debugCompile跟releaseCompile 引入的是不同的包,这样在在 debug 版本上,集成 LeakCanary 执行内存泄漏监测,而在 release 版本上,集成一个无操作的 wrapper ,对程序性能不会有影响
需要依赖:debugCompile'com.squareup.haha:haha:2.0.3',然后另外三个的依赖的版本号要写1.5+,从而获取最新的版本,否则可能会报异常
2:在项目的application类的onCreate()方法中设置LeakCanary,下面是application类代码:
public class MyAppextends Application {
public static MyApp instance;
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
instance =this;
refWatcher = setLeakCanary();
}
private RefWatcher setLeakCanary()
{
//初始化leakCanary,用来检测内存泄漏
if (LeakCanary.isInAnalyzerProcess(this)) {
return RefWatcher.DISABLED;
}
return LeakCanary.install(this);
}
public RefWatcher getRefWatcher() {
if (refWatcher !=null)
{
return refWatcher;
}else {
return null;
}
}
//单例模式中获取唯一的MyApp实例
public static MyApp getInstance() {
if (null ==instance) {
instance =new MyApp();
}
return instance;
}
}
3:在application类中设置完成后,就可以检测activity的内存泄漏了,想要检测fragment的内存泄漏,需要在fragment的onDestroy()方法中加入以下代码:
//用来检测Fragment中的内存泄漏
RefWatcher refWatcher = MyApp.getInstance().getRefWatcher();
if (refWatcher !=null)
{
refWatcher.watch(this);
}
网友评论