• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
韩亚飞_yue31313_韩梦飞沙
未来的某一天你会觉得现在所做的,大部分很烂,小部分很好
博客园    首页    新随笔    联系   管理    订阅  订阅

安卓 内存泄漏检测工具 LeakCanary 使用

韩梦飞沙 yue31313 韩亚飞 han_meng_fei_sha 313134555@qq.com

 

配置 
build.gradle

dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
   testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
 }

 


使用说明

  1. 建立RefWatcher全局变量

  2. 使用RefWatcher去监控引用,Activity,Fragment等中的内存泄漏



例子

第一步:定义RefWathcher全局变量

package com.app.client;

import android.app.Application;
import android.content.Context;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;


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);
    }
}

 

第二步:监控Activity中的内存泄漏问题

package com.app.client;

import android.app.Application;
import android.content.Context;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;


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);
    }
}

 

Manifest配置

 <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

第三步:生成的泄漏结果图

这里写图片描述                   这里写图片描述

韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha
posted @ 2017-08-19 16:14  韩梦飞沙_韩亚飞  阅读(346)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3