在Android中检测内存泄露,除了我没熟知的MAT分析外,还有另外一种方法公选择:LeakCanary
leakcanary是一个由著名的GitHub开源组织Square贡献的开源项目。
使用方法比较简单:
在 build.gradle 中加入

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

在 Application 中:

import com.squareup.leakcanary.LeakCanary;public class ExampleApplication extends Application {  @Override public void onCreate() {    super.onCreate();    LeakCanary.install(this);  }}

这样在debug build 中,如果检测到某个 activity 有内存泄露,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);  }}

在这个过程中你有可能需要设置 File -> Settings ->Build,Execution,Deployment -> Build Tools -> Gradle, Then uncheck “Offline work” on the right.
具体可以参考下面文章:
github:https://github.com/square/leakcanary
LeakCanary 中文使用说明:http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/
demo:https://github.com/liaohuqiu/leakcanary-demo

AndroidExcludedRefs.java忽略的泄漏列表
https://github.com/square/leakcanary/blob/04b0b596dc0119d5056f63186d3f972703e8b507/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidExcludedRefs.java

Leakcanary部分泄露警报无需修复
http://lynn8570.github.io/posts/some%20memory%20leaks%20that%20no%20need%20to%20be%20fixed/

  1. InputMethodManager.sInstance泄露
  2. AsyncQueryHandler 没有quit
  3. TextLine.sCached 泄露 https://github.com/square/leakcanary/pull/283/files

更多相关文章

  1. Android 内存溢出问题分析
  2. 转:Android内存管理机制
  3. Android中App可分配内存的大小
  4. Android性能:内存篇之进程内存管理
  5. Android之——获取进程总数、内存、任务列表
  6. Android内存和外存的学习

随机推荐

  1. PHPMyWind教程:如何把本地测试好的程序发
  2. MySQL常用的函数
  3. 源码方式安装mysql5.5
  4. 数据库连接“Mysql”丢失,缺少mysql.sock
  5. MySQL查询优化技术讲座
  6. MYSQL简单的binlog恢复测试
  7. 如何从php中的数据库表创建表单下拉列表?
  8. 深入浅出MySQL读书笔记(一)
  9. MySQL搜索优化(用子查询替换长正则表达式)
  10. 阿里云服务器MySQL远程连接问题