http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/

LeakCanary 中文使用说明

10 May 2015


LeakCanary

Android 和 Java 内存泄露检测。

“A small leak will sink a great ship.” - Benjamin Franklin

千里之堤, 毁于蚁穴。 -- 《韩非子·喻老》

demo

一个非常简单的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo

开始使用

build.gradle 中加入引用,不同的编译使用不同的引用:

 dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}

Application 中:

public class ExampleApplication extends Application {

  @Override public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}

这样,就万事俱备了! 在 debug build 中,如果检测到某个 activity 有内存泄露,LeakCanary 就是自动地显示一个通知。

为什么需要使用 LeakCanary?

问得好,看这个文章LeakCanary: 让内存泄露无所遁形

如何使用

使用 RefWatcher 监控那些本该被回收的对象。

RefWatcher refWatcher = {...};

// 监控
refWatcher.watch(schrodingerCat);

LeakCanary.install() 会返回一个预定义的 RefWatcher,同时也会启用一个 ActivityRefWatcher,用于自动监控调用 Activity.onDestroy() 之后泄露的 activity。

public class ExampleApplication extends Application {

  public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
} private RefWatcher refWatcher; @Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}

使用 RefWatcher 监控 Fragment:

public abstract class BaseFragment extends Fragment {

  @Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}

工作机制

  1. RefWatcher.watch() 创建一个 KeyedWeakReference 到要被监控的对象。

  2. 然后在后台线程检查引用是否被清除,如果没有,调用GC。

  3. 如果引用还是未被清除,把 heap 内存 dump 到 APP 对应的文件系统中的一个 .hprof 文件中。

  4. 在另外一个进程中的 HeapAnalyzerService 有一个 HeapAnalyzer 使用HAHA 解析这个文件。

  5. 得益于唯一的 reference key, HeapAnalyzer 找到 KeyedWeakReference,定位内存泄露。

  6. HeapAnalyzer 计算 到 GC roots 的最短强引用路径,并确定是否是泄露。如果是的话,建立导致泄露的引用链。

  7. 引用链传递到 APP 进程中的 DisplayLeakService, 并以通知的形式展示出来。

如何复制 leak trace?

在 Logcat 中,你可以看到类似这样的 leak trace:

In com.example.leakcanary:1.0:1 com.example.leakcanary.MainActivity has leaked:

* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #1')
* references com.example.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)
* leaks com.example.leakcanary.MainActivity instance * Reference Key: e71f3bf5-d786-4145-8539-584afaecad1d
* Device: Genymotion generic Google Nexus 6 - 5.1.0 - API 22 - 1440x2560 vbox86p
* Android Version: 5.1 API: 22
* Durations: watch=5086ms, gc=110ms, heap dump=435ms, analysis=2086ms

你甚至可以通过分享按钮把这些东西分享出去。

SDK 导致的内存泄露

随着时间的推移,很多SDK 和厂商 ROM 中的内存泄露问题已经被尽快修复了。但是,当这样的问题发生时,一般的开发者能做的事情很有限。

LeakCanary 有一个已知问题的忽略列表,AndroidExcludedRefs.java,如果你发现了一个新的问题,请提一个 issue 并附上 leak trace, reference key, 机器型号和 SDK 版本。如果可以附带上 dump 文件的 链接那就再好不过了。

对于最新发布的 Android,这点尤其重要。你有机会在帮助在早期发现新的内存泄露,这对整个 Android 社区都有极大的益处。

开发版本的 Snapshots 包在这里: Sonatype's snapshots repository

leak trace 之外

有时,leak trace 不够,你需要通过 MAT 或者 YourKit 深挖 dump 文件。

通过以下方法,你能找到问题所在:

  1. 查找所有的 com.squareup.leakcanary.KeyedWeakReference 实例。
  2. 检查 key 字段
  3. Find the KeyedWeakReference that has a key field equal to the reference key reported by LeakCanary.
  4. 找到 key 和 和 logcat 输出的 key 值一样的 KeyedWeakReference
  5. referent 字段对应的就是泄露的对象。
  6. 剩下的,就是动手修复了。最好是检查到 GC root 的最短强引用路径开始。

自定义

UI 样式

DisplayLeakActivity 有一个默认的图标和标签,你只要在你自己的 APP 资源中,替换以下资源就可。

res/
drawable-hdpi/
__leak_canary_icon.png
drawable-mdpi/
__leak_canary_icon.png
drawable-xhdpi/
__leak_canary_icon.png
drawable-xxhdpi/
__leak_canary_icon.png
drawable-xxxhdpi/
__leak_canary_icon.png
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="__leak_canary_display_activity_label">MyLeaks</string>
</resources>

保存 leak trace

DisplayLeakActivity saves up to 7 heap dumps & leak traces in the app directory. You can change that number by providing R.integer.__leak_canary_max_stored_leaks in your app:

在 APP 的目录中,DisplayLeakActivity 保存了 7 个 dump 文件和 leak trace。你可以在你的 APP 中,定义 R.integer.__leak_canary_max_stored_leaks 来覆盖类库的默认值。

<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="__leak_canary_max_stored_leaks">20</integer>
</resources>

上传 leak trace 到服务器

你可以改变处理完成的默认行为,将 leak trace 和 heap dump 上传到你的服务器以便统计分析。

创建一个 LeakUploadService, 最简单的就是继承 DisplayLeakService

public class LeakUploadService extends DisplayLeakService {
@Override
protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
myServer.uploadLeakBlocking(heapDump.heapDumpFile, leakInfo);
}
}

请确认 release 版本 使用 RefWatcher.DISABLED

public class ExampleApplication extends Application {

  public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
} private RefWatcher refWatcher; @Override public void onCreate() {
super.onCreate();
refWatcher = installLeakCanary();
} protected RefWatcher installLeakCanary() {
return RefWatcher.DISABLED;
}
}

自定义 RefWatcher

public class DebugExampleApplication extends ExampleApplication {
protected RefWatcher installLeakCanary() {
return LeakCanary.install(app, LeakUploadService.class);
}
}

别忘了注册 service:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
>
<application android:name="com.example.DebugExampleApplication">
<service android:name="com.example.LeakUploadService" />
</application>
</manifest>

demo

一个非常简单的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo

转: android 内存检测工具 LeakCanary 说明的更多相关文章

  1. Android 内存泄漏检测工具 LeakCanary(Kotlin版)的实现原理

    LeakCanary 是一个简单方便的内存泄漏检测框架,做 android 的同学基本都收到过 LeakCanary 检测出来的内存泄漏.目前 LeakCanary 最新版本为 2.7 版本,并且采用 ...

  2. Android 内存泄露总结(附内存检测工具)

    https://segmentfault.com/a/1190000006852540 主要是分三块: 静态储存区:编译时就分配好,在程序整个运行期间都存在.它主要存放静态数据和常量. 栈区:当方法执 ...

  3. 【调试】Linux下超强内存检测工具Valgrind

    [调试]Linux下超强内存检测工具Valgrind 内容简介 Valgrind是什么? Valgrind的使用 Valgrind详细教程 1. Valgrind是什么? Valgrind是一套Lin ...

  4. 推荐AndroidGodEye Android性能检测工具

    推荐AndroidGodEye Android性能检测工具 1 介绍 AndroidGodEye是一个可以在PC浏览器中实时监控Android性能数据指标的工具,你可以通过wifi/usb连接手机和p ...

  5. valgrind内存检测工具

    valgrind 那点事 ---------------------------------------内存检测工具 valgrind要使用此工具,可以使用--tool=memcheck 在Valgr ...

  6. android安全检测工具,梆梆安全 - 防止反编译|APP安全加固|应用加固|盗版监测

    android安全检测工具,梆梆安全 - 防止反编译|APP安全加固|应用加固|盗版监测https://dev.bangcle.com/ 业内专业的应用加固服务供应商 帮助数十万APP抵御破解风险,早 ...

  7. linux下内存检测工具的使用和对比

    linux背后隐藏着各种丰富的工具,学会这些工具,让这些工具更好地服务于我们的项目开发,不仅可以提高工作的效率,而且可以增强个人技术力. 参考:http://blog.chinaunix.net/ui ...

  8. android 内存泄漏检测工具 LeakCanary 泄漏金丝雀

    韩梦飞沙 yue31313 韩亚飞 han_meng_fei_sha 313134555@qq.com 内存泄漏检测工具 android 内存泄漏检测工具 ======== 内存泄漏 就是  无用的对 ...

  9. Android内存优化8 内存检测工具2 LeakCanary——直白的展现Android中的内存泄露

    之前碰到的OOM问题,终于很直白的呈现在我的眼前:我尝试了MAT,但是发现不怎么会用.直到今天终于发现了这个新工具: 当我们的App中存在内存泄露时会在通知栏弹出通知: 当点击该通知时,会跳转到具体的 ...

随机推荐

  1. magento 报错及解决方法

    在后台安装主题包时安装出错,重新进入后台进不去,前台也进不去,提示“Service Temporarily Unavailable” 删除根目录下的maintenance.flag文件即可.

  2. 【转】SonarQube配置自定义的CheckStyle代码规则

    原文地址:https://www.jianshu.com/p/ff1d800885ce 惯例第一步肯定是SonarQube的安装与运行配置了,但这部分不在本文主题内,网上一搜一大把,这里就不讲了,大家 ...

  3. strcmp()函数-比较字符串的大小、字符串排序

    1.比较字符串的大小: 用法:strcmp(字符串1,字符串2),若字符串1>字符串2 则返回1,字符串1<字符串2 则返回 -1,相等返回0. 比较两个字符串的算法是:逐个比较两个串中对 ...

  4. CodeForces 672B Different is Good

    链接:http://codeforces.com/problemset/problem/672/B 本文链接:http://www.cnblogs.com/Ash-ly/p/5491176.html ...

  5. 代码编辑器[0] -> Vim/gVim[3] -> 像编程一样使用Vim

    像编程一样使用Vim 目录 为什么是Vim / Why Vim 从hjkl开始上路 -- 使用基本按键进行移动和编辑 / Start from <hjkl> 一次超速和翻车的体验 -- 使 ...

  6. The 15th Zhejiang Provincial Collegiate Programming Contest Sponsored by TuSimple - J CONTINUE...?

    CONTINUE...? Time Limit: 1 Second      Memory Limit: 65536 KB      Special Judge DreamGrid has  clas ...

  7. 洛谷——P1722 矩阵 II

    P1722 矩阵 II 题目背景 usqwedf 改编系列题. 题目描述 如果你在百忙之中抽空看题,请自动跳到第六行. 众所周知,在中国古代算筹中,红为正,黑为负…… 给定一个1*(2n)的矩阵(us ...

  8. Linux下 编译C++/C以及常用的几种命令(ubuntu)

    http://blog.csdn.net/bob1993_dev/article/details/45973919

  9. [Atcoder Regular Contest 064] Tutorial

    Link: ARC064 传送门 C: 贪心+对边界的特殊处理 #include <bits/stdc++.h> using namespace std; typedef long lon ...

  10. [BZOJ 1913] signaling 信号覆盖

    Link:https://www.lydsy.com/JudgeOnline/problem.php?id=1913 TIP:(注意,这题只能输出6位才能过,7位都不行wtf?) Algorithm: ...