2. Motivation
● Testing
○ Automation - Espresso
○ How to monitor Memory leak by passively ?
● Why leakcanary ?
○ Open source
○ Great develop resource
■ okhttp
■ picasso
3. What is leakcanary ?
● A memory leak detection tool
● Avoid OOM (Out Of Memory)
○ A memory leak detection library for Android and
Java
○ java.lang.OutOfMemoryError
● How to integrate leakcanary into Android
project ?
○ here
4.
5. leakcanary
● Automatically detects if an activity is leaking
after Activity.onDestroy() has been called.
● ActivityRefWatcher
○ Application.ActivityLifecycleCallbacks
■ onActivityDestroyed
6. leakcanary
● Detection flow
Watch Check Dump & Parse
If get leak information, it
will send notification and
show message in leak
application
7. leakcanary-Watch
● RefWatcher Class : watch method
a. Give weak wrapper for watched object
public void watch(Object watchedReference, String referenceName) {
if (this == DISABLED) {
return;
}
checkNotNull(watchedReference, "watchedReference");
checkNotNull(referenceName, "referenceName");
final long watchStartNanoTime = System.nanoTime();
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyedWeakReference reference =
new KeyedWeakReference(watchedReference, key, referenceName, queue);
ensureGoneAsync(watchStartNanoTime, reference);
}
8. leakcanary-Check
● RefWatcher Class : ensureGone method
a. Run in background thread
b. Do garbage collection
c. Check watched reference is gone or not
● If not release object well
a. Go to heap dump state
9. leakcanary-Dump
● AndroidHeapDumper : dumpHeap method
a. Create storage file from leak directory
■ /sdcard/Download/leakcanary-${packagename}
b. Dump by Debug.dumpHprofData API
11. Exclude SDK leak
● Yes. There are a number of known memory leaks that
have been fixed over time in AOSP as well as in
manufacturer implementations. When such a leak
occurs, there is little you can do as an app developer to
fix it. For that reason, LeakCanary has a built-in list of
known Android leaks to ignore:
AndroidExcludedRefs.java.
12. Demo
● Debug v.s Production
● Leak in Activity
● Leak in some object
13. Q & A
● How to exclude leak info you want to ignore
?
○ Ignoring specific references
● How do I fix a memory leak?
○ here