Leakcanary is a memory leak detection library that can alert you when a memory leak occurs in our application, including notifications and logs. GitHub
This library is relatively simple to use:
① Add Dependency:
1 Dependencies {2 debugcompile ' com.squareup.leakcanary:leakcanary-android:1.5 '3 releasecompile ' com.squareup.leakcanary:leakcanary-android-no-op:1.5 '4 testcompile ' com.squareup.leakcanary:leakcanary-android-no-op:1.5 '5 }
② Custom Application
1 Public classMyApplicationextendsApplication {2 @Override3 Public voidonCreate () {4 Super. OnCreate ();5 if(Leakcanary.isinanalyzerprocess ( This)) {6 return;7 }8Leakcanary.install ( This);9 }Ten}
That's all you can do.
Here we have a simple example to see how it works, and we all know that memory leaks are more likely to occur because of a life cycle mismatch. Components in Android have a specific life cycle, and when there are non-free variables in those components, the component's life cycle is abnormal, causing it to fail to be released by the GC.
Here is a simple example:
1 Public classSecondactivityextendsappcompatactivity {2 StaticDemo Sdemo;3 4 @Override5 protected voidonCreate (Bundle savedinstancestate) {6 Super. OnCreate (savedinstancestate);7 Setcontentview (r.layout.activity_second);8 if(Sdemo = =NULL) {9Sdemo =NewDemo ();Ten } One finish (); A } - - classDemo { the } - -}
In this activity, there is a static demo instance, and this instance is initialized when the activity is initialized, and then we finish the activity after the initialization is complete.
Because Sdemo is a static variable and is NOT NULL, the GC will not clean it up, and the activity will not execute properly because it holds the static variable, so the activity is compromised.
We open the activity in Mainactivity and launch the app.
An icon will appear in the status bar of the simulator and we can open the following interface:
As you can see, the secondactivity instance has been leaked, as we have analyzed.
In fact, in addition to displaying the leak information in the interface, the leakcanary will also output the exact details of the leak in the log:
It is not difficult to trace the leak in such a way.
Android Development Learning Path-leakcanary use