经典的面试题:

a、怎样在coding过程中避免内存泄露?

b、怎样检测内存泄露?

这两个问题我想大部分Android 职位面试时都会被问到吧。

怎样避免就不赘述了,网上很多答案。

工具呢,当然也有很多,比如DDMS、MAT等,但是怎样在我们编码过程中植入内存检测代码,让我们程序在开发调试阶段就能发现内存泄露呢?好了,现在该大名鼎鼎的LeakCanary出场了,它是Square公司的一个内存探测开源项目。下面就介绍下怎样使用.

1、配置gradle依赖:

  1. debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
  2. releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'

2、初始化Watcher

  1. package com.micky.leakcanarysamples;;
  2. import android.app.Application;
  3. import com.squareup.leakcanary.LeakCanary;
  4. import com.squareup.leakcanary.RefWatcher;
  5. /**
  6. * @Project LeakCanaryTest
  7. * @Packate com.micky.leakcanarysamples;
  8. * @Description
  9. * @Author Micky Liu
  10. * @Email mickyliu@126.com
  11. * @Date 2016-01-04 10:32
  12. * @Version 1.0
  13. */
  14. public class BaseApplication extends Application {
  15. private static BaseApplication instance;
  16. private RefWatcher mRefWatcher;
  17. @Override
  18. public void onCreate() {
  19. super.onCreate();
  20. instance = this;
  21. mRefWatcher = Constants.DEBUG ?  LeakCanary.install(this) : RefWatcher.DISABLED;
  22. }
  23. public static BaseApplication getInstance() {
  24. return instance;
  25. }
  26. public static RefWatcher getRefWatcher() {
  27. return getInstance().mRefWatcher;
  28. }
  29. }

3、在Activity或Fragment中添加检测

  1. package com.micky.leakcanarysamples;
  2. import android.app.Activity;
  3. import android.support.v7.app.AppCompatActivity;
  4. /**
  5. * @Project LeakCanaryTest
  6. * @Packate com.micky.leakcanarysamples;
  7. * @Description
  8. * @Author Micky Liu
  9. * @Email mickyliu@126.com
  10. * @Date 2016-01-04 10:39
  11. * @Version 1.0
  12. */
  13. public class BaseActivity extends AppCompatActivity {
  14. @Override
  15. protected void onDestroy() {
  16. super.onDestroy();
  17. BaseApplication.getRefWatcher().watch(this);
  18. }
  19. }

4、测试

  1. package com.micky.leakcanarysamples;;
  2. import android.os.Bundle;
  3. import android.os.Handler;
  4. /**
  5. * @Project LeakCanaryTest
  6. * @Packate com.micky.leakcanarysamples;
  7. * @Description
  8. * @Author Micky Liu
  9. * @Email mickyliu@126.com
  10. * @Date 2016-01-04 10:29
  11. * @Version 1.0
  12. */
  13. public class TestActivity extends BaseActivity {
  14. private final Handler mHandler = new Handler();
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. //模拟内存泄露
  19. mHandler.postDelayed(new Runnable() {
  20. @Override
  21. public void run() {
  22. }
  23. }, 3 * 60 * 1000);
  24. finish();
  25. }
  26. }

5、测试结果

a、Toast显示(大概10秒左右显示)

b、通知显示

c、桌面自动添加的图表

d、内存泄露列表

e、内存泄露详细

LogCat可以看到日志日下(hprof文件可以用MAT打开进行分析):

  1. 01-04 11:49:41.815 12967-13004/com.micky.leakcanarysamples I/dalvikvm: hprof: dumping heap strings to "/storage/emulated/0/Download/leakcanary/suspected_leak_heapdump.hprof".
  2. 01-04 11:49:42.020 12967-13004/com.micky.leakcanarysamples I/dalvikvm: hprof: heap dump completed (28850KB)

查看自动生成的AndroidManifest文件,LeakCanarySamples/app/build/intermediates/manifests/full/debug/AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.micky.leakcanarysamples"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk
  7. android:minSdkVersion="10"
  8. android:targetSdkVersion="23" />
  9. <!-- To store the heap dumps and leak analysis results. -->
  10. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  11. <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  12. <application
  13. android:name="com.micky.leakcanarysamples.BaseApplication"
  14. android:allowBackup="true"
  15. android:icon="@mipmap/ic_launcher"
  16. android:label="@string/app_name"
  17. android:supportsRtl="true"
  18. android:theme="@style/AppTheme" >
  19. <activity
  20. android:name="com.micky.leakcanarysamples.MainActivity"
  21. android:label="@string/app_name"
  22. android:theme="@style/AppTheme.NoActionBar" >
  23. <intent-filter>
  24. <action android:name="android.intent.action.MAIN" />
  25. <category android:name="android.intent.category.LAUNCHER" />
  26. </intent-filter>
  27. </activity>
  28. <activity android:name="com.micky.leakcanarysamples.TestActivity" />
  29. <service
  30. android:name="com.squareup.leakcanary.internal.HeapAnalyzerService"
  31. android:enabled="false"
  32. android:process=":leakcanary" />
  33. <service
  34. android:name="com.squareup.leakcanary.DisplayLeakService"
  35. android:enabled="false" />
  36. <activity
  37. android:name="com.squareup.leakcanary.internal.DisplayLeakActivity"
  38. android:enabled="false"
  39. android:icon="@drawable/__leak_canary_icon"
  40. android:label="@string/__leak_canary_display_activity_label"
  41. android:taskAffinity="com.squareup.leakcanary"
  42. android:theme="@style/__LeakCanary.Base" >
  43. <intent-filter>
  44. <action android:name="android.intent.action.MAIN" />
  45. <category android:name="android.intent.category.LAUNCHER" />
  46. </intent-filter>
  47. </activity>
  48. </application>
  49. </manifest>

如上所示LeakCanary给我们自动添加了两个Service和一个Activity,并添加了对SD卡的读写权限

It 's so simple.

注:

1、如果在Release模式下请使用RefWatcher.DISABLED

2、在Activity或Fragment 的 Destroy方法中添加检测(很好理解,就是判断一个Activity或Fragment想要被销毁的时候,是否还有其他对象持有其引用导致Activity或Fragment不能被回收,从而导致内存泄露)

源码地址:https://github.com/mickyliu945/LeakCanarySample   点击打开链接

Android内存泄露自动检测神器LeakCanary的更多相关文章

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

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

  2. Android内存泄露总结

    内存泄露是如何产生的? 当一个对象已经不需要再使用了,本该被回收时,而有另外一个正在使用的对象持有它的引用从而导致它不能被回收,这导致本该被回收的对象不能被回收而停留在堆内存中,这就产生了内存泄漏. ...

  3. Android内存泄漏的检测流程、捕捉以及分析

    https://blog.csdn.net/qq_20280683/article/details/77964208 Android内存泄漏的检测流程.捕捉以及分析 简述: 一个APP的性能,重度关乎 ...

  4. (转)专项:Android 内存泄露实践分析

    今天看到一篇关于Android 内存泄露实践分析的文章,感觉不错,讲的还算详细,mark到这里. 原文发表于:Testerhome: 作者:ycwdaaaa ;  原文链接:https://teste ...

  5. CPP-基础:内存泄露及其检测工具

    [转]浅谈C/C++内存泄露及其检测工具   对于一个c/c++程序员来说,内存泄漏是一个常见的也是令人头疼的问题.已经有许多技术被研究出来以应对这个问题,比如 Smart Pointer,Garba ...

  6. Android内存泄露分析之StrictMode

    转载请注明地址:http://blog.csdn.NET/yincheng886337/article/details/50524709 StrictMode(严格模式)使用 StrictMode严格 ...

  7. iOS内存泄漏自动检测工具PLeakSniffer

    新款objective-C内存泄漏自动检测工具 PLeakSniffer , GitHub地址 (https://github.com/music4kid/PLeakSniffer). 背景 前些天读 ...

  8. Android内存泄露---检测工具篇

    内存使用是程序开发无法回避的一个问题.如果我们毫不在意肆意使用,总有一天会为此还账,且痛不欲生...所以应当防患于未然,把内存使用细化到平时的每一行代码中. 内存使用概念较大,本篇先讲对已有app如何 ...

  9. Android内存泄露

    Android 内存泄漏是一个十分头疼的事情.LeakCanary是一款开源软件,主要作用是检测 Android APP 内存泄露.比起以前的 MAT 工具,LeakCanary 有着十分强大的功能, ...

随机推荐

  1. leetcode 【 Search in Rotated Sorted Array II 】python 实现

    题目: 与上一道题几乎相同:不同之处在于array中允许有重复元素:但题目要求也简单了,只要返回true or false http://www.cnblogs.com/xbf9xbf/p/42545 ...

  2. CMD 下运行python的unittest测试脚本无输出

    正常情况下windows的命令行执行python脚本命令: python 脚本名.py 我这样做了,看截图可以看到,并没有期待中那样有一堆高大上的信息输出,反而毛都没有!!!! 于是,我想起了度娘,但 ...

  3. 【LeetCode】汉明距离(Hamming Distance)

    这道题是LeetCode里的第461道题. 题目描述: 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目. 给出两个整数 x 和 y,计算它们之间的汉明距离. 注意: 0 ≤ x,  ...

  4. Struts2拦截器原理

    拦截器是struts2处理的核心,本文主要说struts2的拦截器的基本原理/实现,其它框架处理的东西就不说了,得自己再看了.struts2版本:2.2.3当一个请求来了后,从org.apache.s ...

  5. ALPHA 冲刺(一)

    目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:丹丹 组员7:家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示组内 ...

  6. 201621123034 《Java程序设计》第4周学习总结

    Week04-面向对象设计与继承 1. 本周学习总结 1.1 写出你认为本周学习中比较重要的知识点关键词 答:对象.重载.继承.多态 1.2 尝试使用思维导图将这些关键词组织起来.注:思维导图一般不需 ...

  7. 【bzoj4281】[ONTAK2015]Związek Harcerstwa Bajtockiego 树上倍增+LCA

    题目描述 给定一棵有n个点的无根树,相邻的点之间的距离为1,一开始你位于m点.之后你将依次收到k个指令,每个指令包含两个整数d和t,你需要沿着最短路在t步之内(包含t步)走到d点,如果不能走到,则停在 ...

  8. HDU 2896 病毒侵袭(AC自动机水)

    病毒侵袭 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submi ...

  9. 折线统计(line)

    折线统计(line) 题目描述 二维平面上有n个点(xi, yi),现在这些点中取若干点构成一个集合S,对它们按照x坐标排序,顺次连接,将会构成一些连续上升.下降的折线,设其数量为f(S).如下图中, ...

  10. 分布式文件系统FastDFS集群部署

    1.源码开放下载地址:https://github.com/happyfish100 早期源码开放下载地址:https://sourceforge.net/projects/fastdfs/files ...