作家
登录

带你学开源项目:LeakCanary-如何检测 Activity 是否泄漏

作者: 来源: 2017-05-24 10:06:09 阅读 我要评论

OOM 是 Android 开辟中常见的问题,而内存泄漏往往是祸首祸首。

为了简单便利的检测内存泄漏,Square 开源了 LeakCanary ,它可以及时`测 Activity 是否产生了泄漏,一旦发明就会主动弹出提示及相干的泄漏信息供分析。

本文的目标是试图经由过程分析 LeakCanary 源率攀来商量它的 Activity 泄漏检测机制。

然后再回到膳绫擎的代码。

LeakCanary 应用方法

为了将 LeakCanary 惹人到我们的项目里,我们只须要做以下两步:

  1. dependencies { 
  2.  debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1' 
  3.  releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1' 
  4.  testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'}public class ExampleApplication extends Application {  @Override public void onCreate() {    super.onCreate();    if (LeakCanary.isInAnalyzerProcess(this)) {      // This process is dedicated to LeakCanary for heap analysis. 
  5.       // You should not init your app in this process. 
  6.       return
  7.     } 
  8.     LeakCanary.install(this); 
  9.   } 

可以看出,最症桨?酵是 LeakCanary.install(this); 这么一句话,正式开启了 LeakCanary 的大年夜门,将来它就会主动帮我们检测内存泄漏,并在产生泄漏是弹出通知信息。

大年夜 LeakCanary.install(this); 开端

下面我们来看下它做了些什么?

  1. public static RefWatcher install(Application application) {  return install(application, DisplayLeakService.class, 
  2.       AndroidExcludedRefs.createAppDefaults().build()); 
  3. }public static RefWatcher install(Application application, 
  4.     Class<? extends AbstractAnalysisResultService> listenerServiceClass, 
  5.     ExcludedRefs excludedRefs) {  if (isInAnalyzerProcess(application)) {    return RefWatcher.DISABLED; 
  6.   } 
  7.   enableDisplayLeakActivity(application); 
  8.   HeapDump.Listener heapDumpListener =      new ServiceHeapDumpListener(application, listenerServiceClass); 
  9.   RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs); 
  10.   ActivityRefWatcher.installOnIcsPlus(application, refWatcher);  return refWatcher; 
  11.  

常用的触发 gc 办法是 System.gc() ,那它能达到我们的请求吗?

可以如何来改革 LeakCanary 呢?

起首,我们先看最重要的部分,就是:

  1. RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs); 
  2. ActivityRefWatcher.installOnIcsPlus(application, refWatcher);  

师长教师成了一个 RefWatcher ,这个器械异常关键,大年夜名字可以看出,它是用来 watch Reference 的,也就是用来一个监控引用的对象。然后再把 refWatcher 和我们本身供给的 application 传入到 ActivityRefWatcher.installOnIcsPlus(application, refWatcher); 这句琅绫擎,持续看。

 1/6    1 2 3 4 5 6 下一页 尾页

  推荐阅读

  一个可以查看Linux当前缓存了哪些大文件的小工具

Linux 用户可能经常碰到的一个问题是,机械有 16GB 内存之多,运行的过程也不多,然则剩下的 free 内存并不多,大年夜部分都被 buff 和 cache 占用了(比如下面我的 PC)。$ free -h >>>详细阅读


本文标题:带你学开源项目:LeakCanary-如何检测 Activity 是否泄漏

地址:http://www.17bianji.com/lsqh/35385.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)