Start using
In build.gradle
addition to the references, different compilations use different references:
dependencies { debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.3‘ releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.3‘ }
In the Application
:
public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); }}
How to use
Use RefWatcher
to monitor those objects that should be recycled.
RefWatcher refWatcher = {...};// 监控refWatcher.watch(schrodingerCat);
LeakCanary.install()
will return a predefined activity that is RefWatcher
also enabled ActivityRefWatcher
for automatic monitoring after a call is Activity.onDestroy()
released.
PublicClassExampleapplicationExtendsApplication{PublicStaticRefwatcherGetrefwatcher(ContextContext){ExampleapplicationApplication=(Exampleapplication)context. (); return application. Refwatcher} private refwatcher refwatcher @Override public void oncreate () {super. Oncreate (); refwatcher = leakcanary. Install (this} /span>
Using RefWatcher
monitoring Fragment:
Publicabstract class basefragment extends Fragment { @Override public void ondestroy< c10> () { Super. OnDestroy(); refwatcher refwatcher = exampleapplication. Getrefwatcher(getactivity()); refwatcher. Watch(this); }}< /c14>
Working mechanism
RefWatcher.watch()
Create a keyedweakreference to the object to be monitored.
Then the background thread checks if the reference is cleared, and if not, the GC is called.
If the reference is still not cleared, dump the heap memory into a file in the APP's file system .hprof
.
There is one in another process that HeapAnalyzerService
HeapAnalyzer
uses haha to parse this file.
Thanks to the unique reference key, HeapAnalyzer
locate KeyedWeakReference
and locate the memory leak.
HeapAnalyzer
Calculates the shortest strong reference path to the GC roots and determines whether it is a leak. If so, establish a chain of references that leads to leaks.
The reference chain is passed into the APP process and is displayed in the DisplayLeakService
form of notifications.
Leakcanary Android and Java memory leak detection.