使用LeakCanary分析并解决Android内存泄露
LeakCanary是一款内存泄露分析工具,至于什么是内存泄露网上有很多帖子,这里就不废话了,改工具是在app里植入一个新进程的和一个新入口的工具组件,也就是说使用了leakcanary的app安装后会在桌面看到两个app入口,卸载其中一个另外一个也会被卸载,并且两个入口运行在不同的进程。而在leakcanary入口里可以看到主app里内存泄露的所有信息。这里要说一下,当主app发生内存后,需要一段时间才能在leakcanary里看到,而不是马上就有,因为hprof文件的导出和分析需要很长时间,直到在notifycation出现通知才在leakcanary里能看到细节信息,LeakCanary托管在github上:点击进入
Andorid app查找内存泄露的一般步骤
- 运行app,先用DDMS内存管理点击GC按钮触发GC或者在adb shell下使用dumpsys meminfo 来观察app是否有内存泄露的嫌疑,这里一定要在app上多操作然后不断的观察内存变化的情况,如果是一直增加的话就可以怀疑有内存泄露的情况,有了leakcanary此步骤可以说在某种程度下能忽略
- 在项目里加入leakcanary,如果用的是AndroidStudio的话在gradle里加入如下代码:
dependencies {
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}
- 然后在自定义application并在manifest里申明:
public class TestMemApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Logger.addLogAdapter(new AndroidLogAdapter());
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
// Normal app init code...
}
}
- 不断的在app里操作,如果有内存泄露的地方会有提示,然后查看,Leakcanary集成以后会在你的app进程之外开启一个新进程,也就是说如果你安装了包含leakcanary的app会发现桌面多出了两个图标,其中之一就是leakcanary,另外一个就是你自己的app了,可以通过点击leakcanary的图标进去查看内存泄露的相关信息。