如何使用泄漏金丝雀
我目前在我的应用程序中遇到 OutOfMemoryError。我尝试过使用MAT进行调试,但是在一些活动中仍然很难找到泄漏。然后我找到了LeakCanary,它似乎更简单,更容易使用,但是即使在Google上,我也找不到任何使用Leak Canary的初学者分步指南。我已经通过build.gradle中的依赖项安装了LeakCanary,这是我到目前为止得到的:
示例应用.java
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);
}
final class KeyedWeakReference extends WeakReference<Object> {
public final String key;
public final String name;
KeyedWeakReference(Object referent, String key, String name,
ReferenceQueue<Object> referenceQueue) {
super(checkNotNull(referent, "referent"), checkNotNull(referenceQueue, "referenceQueue"));
this.key = checkNotNull(key, "key");
this.name = checkNotNull(name, "name");
}
}
public void watch(Object watchedReference, String referenceName) {
checkNotNull(watchedReference, "watchReference");
checkNotNull(referenceName, "referenceName");
if(debuggerControl.isDebuggerAttached()) {
return;
}
final long watchStartNanoTime = System.nanoTime();
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyedWeakReference reference =
new KeyedWeakReference(watchedReference, key, referenceName, queue);
watchExecutor.execute()
}
}
假设我有一个活动,我希望LeakCanary观看一个对象
样品活性.java
public class SampleActivity extends Activity implements View.OnClickListener {
ImageView level001, level002;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_level);
level001 = (ImageView) findViewById(R.id.level001);
level002 = (ImageView) findViewById(R.id.level002);
// Do all kinds of functions
// How do I use LeakCanary to watch these objects?
}
}
现在,我如何使用 LeakCanary 查看哪个对象导致内存泄漏?