内存泄漏监测-LeakCanary

时间:2023-03-09 00:48:28
内存泄漏监测-LeakCanary

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

LeakCanary出处:

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

square 公司

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

还有很多开源看下图

内存泄漏监测-LeakCanary

使用方法:

android studio

添加依赖:

 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:自行下包

使用方法很简单,在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();
}

结果如下:

内存泄漏监测-LeakCanary