Android内存管理(14)*使用开源库LeakCanary检查内存泄漏

1.简介

  它是一个非常简单好用的内存泄漏检测工具库。可以轻松检测Activity,Fragment的内存泄漏。如果有内存泄漏,它会产生一个通知。

  

2.资料

官网:

  https://github.com/square/leakcanary

官网教程:

  https://github.com/square/leakcanary/wiki/FAQ

中文教程:

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

3.基本流程

3.1 在build.gradle中添加引用库

1 dependencies {
2    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
3    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
4    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
5  }

3.2 在manifest.xml中添加一个Application类.

1 ...
2 <application
3         android:allowBackup="false"
4         android:name="com.e.weixin.main.presenter.WeiXinApplication"
5         android:icon="@drawable/ic_launcher"
6         android:label="@string/app_name"
7         android:theme="@style/AppBaseTheme" >
8 ...

3.3 然后用RefWatcher监视它

 1 public class ExampleApplication extends Application {
 2 
 3   public static RefWatcher getRefWatcher(Context context) {
 4     ExampleApplication application = (ExampleApplication) context.getApplicationContext();
 5     return application.refWatcher;
 6   }
 7 
 8   private RefWatcher refWatcher;
 9 
10   @Override public void onCreate() {
11     super.onCreate();
12     refWatcher = LeakCanary.install(this);
13   }
14 }

  这样当有Activity中产生内存漏泄时,就会有通知。

  可以在想要检测的Fragment中添加如下代码:

1 public abstract class BaseFragment extends Fragment {
2 
3   @Override public void onDestroy() {
4     super.onDestroy();
5     RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
6     refWatcher.watch(this);
7   }
8 }

4.自定义LeakCanary

  官网: https://github.com/square/leakcanary/wiki/Customizing-LeakCanary

  为了不与其它使用LeakCanary库的应用产生同名的接收通知程序,可以自定义  __leak_canary_display_activity_label

1    <!-- TODO: Remove or change this placeholder text -->
2     <string name="hello_blank_fragment">Hello blank fragment</string>
3     <string name="__leak_canary_display_activity_label">WeiXinLeaks</string>
4     <integer name="__leak_canary_max_stored_leaks">20</integer>
5     <integer name="leak_canary_watch_delay_millis">1500</integer>

 

posted @ 2016-04-04 21:19  f9q  阅读(567)  评论(0编辑  收藏  举报