LeakCanary-source code,
This article mainly introduces the implementation process of LeakCanary. Some specific code is not described in detail.
1. LeakCanary involved in graph-like relationship Parsing
2. Analyze the LeakCanary execution sequence diagram
3. LeakCanary Execution Process Analysis
/*** Class: ExampleApplication. java */protected void setupLeakCanary () {if (LeakCanary. isInAnalyzerProcess (this) {// This process is dedicated to LeakCanary for heap analysis. // You shoshould not init your app in this process. return;} enabledStrictMode (); LeakCanary. install (this );}
Before installing LeakCanary, determine whether the current process is the remote analysis process of HeapAnalyzerService. If it is an analysis process, it will be returned directly. Otherwise, call the install () method of LeakCanary, which is the entry point.
/*** Creates a {@ link RefWatcher} that works out of the box, and starts watching activity * references (on ICS + ). * Category: LeakCanary. java */public static RefWatcher install (Application application) {return refWatcher (application ). listenerServiceClass (DisplayLeakService. class ). excludedRefs (AndroidExcludedRefs. createAppDefaults (). build ()). buildAndInstall ();}
Create a RefWatcher and start listening for activity reference. Note: If you need to listen to fragment, You need to manually listen. The refWatcher (application) method returns the AndroidRefWatcherBuilder object, listenerServiceClass (DisplayLeakService. class) performs callback listening on Parsing results. display service and excludedRefs (AndroidExcludedRefs. createAppDefaults (). build () sets the memory leakage to be filtered, generally known sdk Memory leakage and third-party Library Memory leakage. Then, call buildAndInstall ().
/*** Creates a {@ link RefWatcher} instance and starts watching activity references (on ICS + ). * Category: AndroidRefWatcherBuilder. java */public RefWatcher buildAndInstall () {RefWatcher refWatcher = build (); if (refWatcher! = DISABLED) {LeakCanary. enableDisplayLeakActivity (context); ActivityRefWatcher. install (Application) context, refWatcher);} return refWatcher ;}
Builid calls the parent class method to create RefWatcher, and then calls ActivityRefWatcher. install (Application) context, refWatcher) to start monitoring activity. First, let's take a look at the build () method of the parent class:
/*** Creates a {@ link RefWatcher }. * Class: RefWatcherBuilder. java */public final RefWatcher build () {if (isDisabled () {return RefWatcher. DISABLED;} ExcludedRefs excludedRefs = this. excludedRefs; if (excludedRefs = null) {excludedRefs = defaultExcludedRefs ();} HeapDump. listener heapDumpListener = this. heapDumpListener; if (heapDumpListener = null) {heapDumpListener = defaultHeapDumpListener ();} DebuggerControl debuggerControl = this. debuggerControl; if (debuggerControl = null) {debuggerControl = defaultDebuggerControl ();} HeapDumper heapDumper = this. heapDumper; if (heapDumper = null) {heapDumper = defaultHeapDumper ();} WatchExecutor watchExecutor = this. watchExecutor; if (watchExecutor = null) {watchExecutor = defaultWatchExecutor ();} GcTrigger gcTrigger = this. gcTrigger; if (gcTrigger = null) {gcTrigger = callback ();} return new RefWatcher (watchExecutor, debuggerControl, gcTrigger, heapDumper, heapDumpListener, excludedRefs );}
Calls the subclass AndroidRefWatcherBuilder. java method defaultHeapDumpListener (), create ServiceHeapDumpListener assign heapDumpListener (ServiceHeapDumpListener is used to callback HeapAnalyzerService for parsing. hprof source file), defaultHeapDumper () Create AndroidHeapDumper assign heapDumper (AndroidHeapDumper for dump. hprof source file). After initializing each parameter, create a RefWatcher. Look back at ActivityRefWatcher. install (Application) context, refWatcher );
/*** Class: ActivityRefWatcher. java */public static void install (Application application, RefWatcher refWatcher) {new ActivityRefWatcher (application, refWatcher). watchActivities ();}
Start to monitor the activity. For more information, see watchActivities.
/*** Class: ActivityRefWatcher. java */public void watchActivities () {// Make sure you don't get installed twice. stopWatchingActivities (); application. registerActivityLifecycleCallbacks (lifecycleCallbacks );}
Register the application callback. For more information, see lifecycleCallbacks,
/*** Class: ActivityRefWatcher. java */private final Application. activityLifecycleCallbacks lifecycleCallbacks = new Application. activities () {@ Override public void onActivityCreated (Activity activity, Bundle savedInstanceState) {}@ Override public void onActivityStarted (Activity activity) {}@ Override public void onActivityResumed (Activity activity) {}@ Override public void onActivityPaused (Activity activity) {}@ Override public void onActivityStopped (Activity activity) {}@ Override public void onActivitySaveInstanceState (Activity activity Activity, Bundle outState) {}@ Override public void onActivityDestroyed (Activity activity) {ActivityRefWatcher. this. onActivityDestroyed (activity );}};
Let's look at ActivityRefWatcher. this. onActivityDestroyed (activity,
/*** Class: ActivityRefWatcher. java */void onActivityDestroyed (Activity activity) {refWatcher. watch (activity );}
The activity is automatically monitored here, so we do not need to manually monitor the activity, but this is why we need to manually monitor fragment. Next, let's take a look at how refWatcher monitors the referenced object to determine whether it is memory leakage. Follow up to see the specific implementation code.
/*** Watches the provided references and checks if it can be GCed. this method is non blocking, * the check is done on the {@ link WatchExecutor} this {@ link RefWatcher} has been constructed *. ** @ param referenceName An logical identifier for the watched object. * Class: RefWatcher. java */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 );}
Create a corresponding weak reference for the referenced object and associate it with the queue. The queue is ReferenceQueue. All weak references are recycled and enter the queue. Then, call the ensureGoneAsync method to see the specific implementation code,
/*** Class: RefWatcher. java */@ SuppressWarnings ("ReferenceEquality") // Explicitly checking for named null. retryable. result ensureGone (final KeyedWeakReference reference, final long watchStartNanoTime) {long gcStartNanoTime = System. nanoTime (); long watchDurationMs = NANOSECONDS. toMillis (gcStartNanoTime-watchStartNanoTime); // remove the recycled object removeWeaklyReachableReferences (); if (debuggerControl. isDebug GerAttached () {// The debugger can create false leaks. return RETRY;} // determines whether the object is recycled. if (gone (reference) {return DONE;} // manually GC gcTrigger. runGc (); // remove the recycled object removeWeaklyReachableReferences (); if (! Gone (reference) {// if not recycled, dump original information long startDumpHeap = System. nanoTime (); long gcDurationMs = NANOSECONDS. toMillis (startDumpHeap-gcStartNanoTime); File heapDumpFile = heapDumper. dumpHeap (); if (heapDumpFile = RETRY_LATER) {// cocould not dump the heap. return RETRY;} long heapDumpDurationMs = NANOSECONDS. toMillis (System. nanoTime ()-startDumpHeap); heapdumpListener. analyze (new HeapDump (heapDumpFile, reference. key, reference. name, excludedRefs, watchDurationMs, gcDurationMs, heapDumpDurationMs) ;}return DONE ;}
Remove recycled objects and determine whether the corresponding weak reference is recycled. If not, manually trigger GC to remove recycled objects, if the weak reference still exists, the original information corresponding to dump is called for callback parsing. heapdumpListener is the former ServiceHeapDumpListener. Let's take a look at heapdumpListener. the specific implementation of analyze,
/*** Class: ServiceHeapDumpListener. java */@ Override public void analyze (HeapDump heapDump) {checkNotNull (heapDump, "heapDump"); HeapAnalyzerService. runAnalysis (context, heapDump, listenerServiceClass );}
Call the Resolution service to parse the source file and check what is done in it,
/*** Class: HeapAnalyzerService. java */@ Override protected void onHandleIntent (Intent intent) {if (intent = null) {CanaryLog. d ("HeapAnalyzerService received a null intent, ignoring. "); return;} String listenerClassName = intent. getStringExtra (LISTENER_CLASS_EXTRA); HeapDump heapDump = (HeapDump) intent. getSerializableExtra (HEAPDUMP_EXTRA); HeapAnalyzer heapAnalyzer = new HeapAnalyzer (heapDump. excludedRefs); AnalysisResult result = heapAnalyzer. checkForLeak (heapDump. heapDumpFile, heapDump. referenceKey); AbstractAnalysisResultService. sendResultToListener (this, listenerClassName, heapDump, result );}
Call HeapAnalyzer. checkForLeak () to parse the source file, call the DisplayLeakService parent class method sendResultToListener to start DisplayLeakService, and send the parsed content to DisplayLeakService through onHeapAnalyzed (heapDump, result.
/*** Class: DisplayLeakService. java */@ Override protected final void onHeapAnalyzed (HeapDump heapDump, AnalysisResult result) {String leakInfo = leakInfo (this, heapDump, result, true); CanaryLog. d ("% s", leakInfo); boolean resultSaved = false; boolean shouldSaveResult = result. leakFound | result. failure! = Null; if (shouldSaveResult) {heapDump = dumps (heapDump); resultSaved = saveResult (heapDump, result);} PendingIntent pendingIntent; String contentTitle; String contentText; if (! ShouldSaveResult) {contentTitle = getString (R. string. leak_canary_no_leak_title); contentText = getString (R. string. leak_canary_no_leak_text); pendingIntent = null;} else if (resultSaved) {pendingIntent = DisplayLeakActivity. createPendingIntent (this, heapDump. referenceKey); if (result. failure = null) {String size = format1_filesize (this, result. retainedHeapSize); String className = classSimpleName (result. className); if (result. excludedLeak) {contentTitle = getString (R. string. leak_canary_leak_excluded, className, size);} else {contentTitle = getString (R. string. leak_canary_class_has_leaked, className, size) ;}} else {contentTitle = getString (R. string. leak_canary_analysis_failed);} contentText = getString (R. string. leak_canary_icationication_message);} else {contentTitle = getString (R. string. leak_canary_could_not_save_title); contentText = getString (R. string. leak_canary_could_not_save_text); pendingIntent = null;} // New notification id every second. int notificationId = (int) (SystemClock. uptimeMillis ()/1000); showNotification (this, contentTitle, contentText, pendingIntent, icationicationid); afterDefaultHandling (heapDump, result, leakInfo );}
Generate the result file required by display. The pop-up box prompts the memory leakage information. Now we know the whole process from monitoring to parsing and then displaying the leaked information.