使用LeakCanary检测内存泄漏

一、介绍

在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>
 
 大功告成 编译运行吧~ 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值