Square/leakcanary
Udacity/sunshine-version-2
Add Leakcanary Dependency Package
Add the following dependencies under Build.gradle under the main module app:
‘com.squareup.leakcanary:leakcanary-android:1.3.1‘ ‘com.squareup.leakcanary:leakcanary-android-no-op:1.3.1‘
Turn on Leakcanary Add Application sub-class
First create a exampleapplication, which inherits from application, and adds the following code to the OnCreate method of the class to turn on Leakcanary monitoring:
LeakCanary.install(this);
Registering exampleapplication in the configuration file
In AndroidManifest.xml the application label, add the following information:
android:name=".ExampleApplication"
Installing apps to your phone at this time will automatically install a leaks application, such as:
Make a memory leak point
Create a ActivityManager class, Singleton pattern, which has an array to hold Activity :
PackageCom.example.android.sunshine.app;Importandroid.app.Activity;ImportAndroid.util.SparseArray;ImportAndroid.view.animation.AccelerateInterpolator;ImportJava.util.List;/** * Created by Wuxian on 15/10/23. * * Public class activitymanager { Privatesparsearray<activity> container =NewSparsearray<activity> ();Private intKey =0;Private StaticActivitymanager minstance;Private Activitymanager(){} Public StaticActivitymanagergetinstance(){if(Minstance = =NULL) {minstance =NewActivitymanager (); }returnMinstance; } Public void addactivity(Activity activity) {container.put (key++,activity); }}
Then in DetailActivity the method in the onCreate activity array currently added to ActivityManager :
@Override protected void OnCreate (Bundle savedinstancestate) {Super. OnCreate(savedinstancestate);Setcontentview (R. Layout. Activity_detail);Activitymanager. getinstance(). Addactivity(this);if (savedinstancestate = = null) {//Create the detail fragment and AddIt to the activity//using a fragment transaction. Bundle arguments = new Bundle ();Arguments. Putparcelable(detailfragment. DETAIL_uri, Getintent (). GetData());Detailfragment fragment = new Detailfragment ();Fragment. Setarguments(arguments);Getsupportfragmentmanager (). BeginTransaction(). Add(R. ID. Weather_detail_container, fragment). Commit();} }
We jump from the first page to the Detail page will enter the DetailActivity onCreate method, and then will be currently activity added to the array, when returned, we did not remove him from the array. When it enters again, it creates a new one activity and adds it to the array, but the previous activity one is still referenced and cannot be freed, but this is activity no longer used, which creates a memory leak. Let's see LeakCanary how this problem is reported.
Demonstrate
The parsing process is a bit time-consuming, so it takes a while to wait for a moment in the leaks application, and when we open a message, we see a detailed leak:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Memory Leak Detection-leakcanary