前言
Android开发中内存泄漏的问题一直是比较头疼的问题,因为它发生了也很难被发现,在我们不知情的情况下也就没办法去修复这个问题。
LeakCanary的开源给我们一个简便的解决方案。
一、初始化
1.配置依赖:
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
2.在Application中初始化:
public class MyApplication extends Application {
private static MyApplication instance;
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
instance = this;
mRefWatcher = !LeakCanary.isInAnalyzerProcess(this) ? LeakCanary.install(this) : RefWatcher.DISABLED;
}
public static MyApplication getInstance() {
return instance;
}
public static RefWatcher getRefWatcher() {
return getInstance().mRefWatcher;
}
}
二、检测
在BaseActivity中的OnDestory()中加入检测方法:
@Override
protected void onDestroy() {
super.onDestroy();
MyApplication.getRefWatcher().watch(this);
}
然后就可以模拟一个内存泄漏的例子来试试看了。
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//模拟内存泄露
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
}
}, 3 * 60 * 1000);
}
这个例子是Activity试图销毁时,仍被handler隐式持有,所以无法销毁引起内存泄漏。
三、获取泄漏信息
1.首先会有一个Toast弹出。

2.桌面上会有一个对应的Leaks App生成:

3.等待一会之后,在通知栏中会有一个notifacation出现:

4.点击这个notification会跳转到新生成的那个Leaks中去

这里就会有内存泄漏的信息了。
本文介绍如何使用LeakCanary进行Android应用内存泄漏的检测与定位。通过配置依赖及在Application中初始化,结合BaseActivity的OnDestory()方法,可以有效地监控内存泄漏,并通过LeakCanary提供的工具查看泄漏详情。
4万+

被折叠的 条评论
为什么被折叠?



