Overview
Memory leak refers to the failure of the program to release memory that is no longer in use due to negligence or error. So in Android, when an object holds a reference to the activity, if the object cannot be reclaimed by the system, then when the activity is no longer being used, the activity will not be reclaimed by the system, so there has been a memory leak. There is no effect on memory leaks that occur two times in an application, but after prolonged use, if there is a large amount of activity that cannot be recycled by GC, it will eventually cause Oom to occur. So we're here to analyze the common factors that lead to memory leaks and how to detect memory leaks.
Common factors that cause memory leaksScenario One: Static activity and view
Static variables activity and view cause a memory leak, and in the following code, the context and textview of the activity are set to static objects, resulting in a memory leak.
ImportAndroid.content.Context;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.widget.TextView; Public class mainactivity extends appcompatactivity { Private StaticContext context;Private StaticTextView TextView;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Context = This; TextView =NewTextView ( This); }}
Scenario Two: Thread, anonymous class, inner class
In the following code, there is a non-static anonymous class object thread that implicitly holds the reference leakactivity of an external class, resulting in a memory leak. Similarly, if this thread is the inner class of leakactivity rather than an anonymous inner class, he also holds references to external classes that cause memory leaks. It is only necessary to define a static inner class for the thread anonymous class (the static inner class does not hold an implicit reference to the outer class).
Public class leakactivity extends appcompatactivity { @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_leak); Leakfun (); }Private void Leakfun(){NewThread (NewRunnable () {@Override Public void Run() {Try{Thread.Sleep (integer.max_value); }Catch(Interruptedexception e) {E.printstacktrace (); } } }); }}
Scenario Three: Animation
There is a class of infinite looping animations in the property animation, and if you play this type of animation in activity and stop the animation in OnDestroy, the animation will continue to play until the activity is held by view, causing the activity to not be released. Solving this kind of problem requires the early activity OnDestroy to call Objectanimator.cancel () to stop the animation.
Public class leakactivity extends appcompatactivity { PrivateTextView TextView;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_leak); TextView = (TextView) Findviewbyid (R.id.text_view); Objectanimator objectanimator = Objectanimator.offloat (TextView,"Rotation",0, the); Objectanimator.setrepeatcount (Valueanimator.infinite); Objectanimator.start (); }}
Scenario Four: Handler
For handler memory leaks in (Android messaging mechanism--handler working process) [http://blog.csdn.net/ljd2038/article/details/50889754] This article has been described in detail, Not to repeat it.
Scenario Five: Improper use of third-party libraries
For the use of some third open source frameworks such as Eventbus,rxjava, the memory leak will result if the activity is not de-subscribed before it is destroyed.
using MAT to detect memory leaks
After the introduction of a common memory leak, here's a look at using the mat (memory Analysis Tool) to detect the leak. The mat is: http://www.eclipse.org/mat/downloads.php.
Here's an error code that will cause a memory leak.
public class leakactivity extends appcompatactivity { @Override protected void oncreate (Bundle savedinstancestate) {super . OnCreate (savedinstancestate); Setcontentview (R.layout.activity_leak); Eventbus.getdefault (). Register (this ); } @Subscribe public void subscriber (String s) {}}
There is a memory leak in the above code because Eventbus is not de-registered. Here's an example of how to analyze a memory leak in this section of code.
Open the monitors in Androidstudio to see the following interface.
Here you can see that when the application just started, the memory used is 15M, and then we now start to operate the app, repeatedly into the exit leakacticity. Click on the GC button on the as above. This time we are looking at memory usage.
Here we can see that the memory continues to increase, has reached 33M, and cannot be reclaimed by GC. So we can judge that this is the case of a memory leak inevitably. Then click the Dump Java heap button now and see the generated hprof file in the captures window. However, the generated hprof file is not in the standard format, and we need to convert it through the tool Hprof-conv provided by the SDK, which is in the Platform-tools directory of the SDK. The following commands are executed:
hprof-conv XXX.hprof converted-dump.hprof
Of course, you can omit this step in the Androidstudio, you can export the standard format of the Hprof file directly.
You can open the exported hprof file by using the Mat tool. Open the interface as shown in:
The most common thing we use in the mat is histogram and Dominator Tree, which correspond to the A and B buttons respectively. Histogram can see the number of different types of buffer in memory and the size of memory, while Dominator tree sorts the objects in memory in order from large to small, and can parse the reference relationship between objects. Let's introduce the meaning of the two symbols in mat here.
- Shallowheap: The amount of memory occupied by the object itself, excluding the object he references
- Retainedheap: The size of the memory occupied by the object itself, plus its direct or indirect reference to the size of the object
Histogram
Since the general memory leak in Android mostly appears in Acivity, you can click the Histogram button and search
Activity.
Here you can see that there are 69 objects in leakactivity, which can basically determine the case of a memory leak, which can be analyzed by looking at the reference chain of the GC object. Click the right mouse button to select Merge shortest paths to GC roots and select exclude Weak/soft references to exclude weak and soft references.
After you exclude soft references and weak references as shown:
Here you can see the leakactivity memory leaks caused by eventbus.
In histogram, you can also view an object that contains references to those objects. For example, to see the references contained in leakactivity now, you can click the right mouse button and select the With incoming reference in list objects. The With Outcoming reference indicates that the selected object holds references to those objects.
Dominator Tree
Now we can click on the Dominator Tree button and search
Activity. You can see the following as shown:
There are a lot of leakactivity here. Then click the right mouse button to select path to GC roots->exclude Weak/soft references to exclude weak and soft references.
You can then see the following result, which is still a memory leak caused by Eventbus:
Summary
Memory leaks are often overlooked by us, but when a large amount of memory leaks leads to oom. The impact of it is also not to be underestimated. Of course, in addition to the above analysis of memory leaks, we can also analyze memory leaks through leakcanary. The use of leakcanary is not described here in detail.
Memory leaks optimized for Android performance