内存泄漏监测-LeakCanary

内存泄漏监测方法之使用LeakCanaryandroid

LeakCanary出处:git

github:https://github.com/square/leakcanary/issuesgithub

square 公司app

这个公司大名不知道,但你必定知道OKHTTP.eclipse

还有不少开源看下图ide

 

使用方法:this

android studio spa

添加依赖:debug

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

eclipse:自行下包code

使用方法很简单,在application install就能够了。

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        LeakCanary.install(this);
    }
}

如如应用存在多个进程,application onreate 会调用屡次。这么写是否是有问题。Install屡次。

既然是大厂出的东西,他们是已经考虑到了。

看源码:

/**
   * Creates a {@link RefWatcher} that reports results to the provided service, and starts watching
   * activity references (on ICS+).
   */
  public static RefWatcher install(Application application,
      Class<? extends AbstractAnalysisResultService> listenerServiceClass,
      ExcludedRefs excludedRefs) {
    //判断是否在Analyzer进程里
    if (isInAnalyzerProcess(application)) {
      return RefWatcher.DISABLED;
    }
    enableDisplayLeakActivity(application);
    HeapDump.Listener heapDumpListener =
        new ServiceHeapDumpListener(application, listenerServiceClass);
    RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
    ActivityRefWatcher.installOnIcsPlus(application, refWatcher);
    return refWatcher;
  }

固然也能够:

if (LeakCanary.isInAnalyzerProcess(this)) {
  return;
}

这么判断。

经过以上操做,功能已经能够使用了,十分傻瓜。

 

上手试试加如下加代码:

public class LoginActivity extends Activity {
    static Thread t;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                }
            }
        });
        t.start();

        finish();
    }

结果以下:

 

相关文章
相关标签/搜索