android 内存检测框架,Android项目内存泄漏检测

关于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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值