一、介绍
在Android开发中经常会遇到内存泄漏的问题,作为一个Android新手很难找到什么地方内存泄漏了,直到今天我发现了这个工具LeakCanary,帮助你在开发阶段方便的检测出内存泄露的问题,它能直接弹出内存泄漏的信息,而且使用也十分简单。LeakCanary是良心企业Square开源的一个非常有用的工具, 强烈推荐, 我第一时间使用也帮助我发现了不少问题。这是它的github地址点击打开链接
二、使用
在
build.gradle
中加入引用,不同的编译使用不同的引用:
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
<span style="font-family: Arial, Helvetica, sans-serif;">在项目的Application中加上:</span>
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);
......
}
.....
}
然后再Acitivty中添加如下代码进行监控
<span style="font-family: Arial, Helvetica, sans-serif;"> <service</span>
android:name="com.squareup.leakcanary.internal.HeapAnalyzerService"
android:enabled="false"
android:process=":leakcanary" />
<service
android:name="com.squareup.leakcanary.DisplayLeakService"
android:enabled="false" />
<activity
android:name="com.squareup.leakcanary.internal.DisplayLeakActivity"
android:enabled="false"
android:icon="@drawable/__leak_canary_icon"
android:label="@string/__leak_canary_display_activity_label"
android:taskAffinity="com.squareup.leakcanary"
android:theme="@style/__LeakCanary.Base" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
大功告成 编译运行吧~