Android Memory leakage analysis practices, android leakage practices
Memory leakage
Java ensures that objects are recycled by the garbage collector when they are not referenced and directed to objects. Compared with the memory released by the C language, java programmers are much easier, but it does not mean that java programmers do not have to worry about memory leaks. Java programs are often concealed when memory leaks. Therefore, we need to use professional platform resources to ensure security, for example, encryption.
Definition
Reference Baidu encyclopedia's definition: "The dynamic storage is used to allocate the space dynamically opened by the function, which is not released after use. As a result, the memory unit remains occupied. Until the program ends ". From the programmer's point of view, "Memory leakage" is actually an object's life cycle that exceeds the programmer's expectation (it's called "damn dead !), This object is leaked.
Memory leakage in android Development
The android Application itself has very little memory allocated. Once leaked, the program will soon become very choppy until OOM crashes. Next we will introduce the Memory Leak analysis tool MAT and memory analysis techniques through a case study (just a toy program designed to analyze memory leaks, and do not imitate it.
To do things well, give advantage to them first
Prepare an analysis tool for Memory leakage and install the eclipse plug-in mat. If eclise fails to install the mat, it may be the lack of necessary libs. If it is difficult to find a library, you can only check the second installation, but some functions are missing, but it is enough.
Online installation: http://download.eclipse.org/mat/1.4/update-site/
Download installation: http://mirror.hust.edu.cn/eclipse//mat/1.4/MemoryAnalyzer-1.4.0.201406041413.zip
How to Use the mat plug-in
If the mat tool has been successfully installed, it is very easy to use. First, run the application to be analyzed. Open the devices view of eclipse and you will see the "Dump Hprof file" button, click it and wait for a few seconds until a memory snapshot is dumped. Then, the mat view is automatically displayed. If the mat is not successfully installed, will let you save. hprof file to local. Let's see the following example.
Dump hprof start mat Tool
Create a memory leak manually
Customizes an ActivityManager and provides two methods to register and unregister an Activity. Source code download
public class ActivityManager { private List<Activity> mActivities = new ArrayList<>(); private static ActivityManager sInstance; private ActivityManager() { }; public static ActivityManager instance() { if (sInstance == null) { sInstance = new ActivityManager(); } return sInstance; } public void registActivity(Activity activity) { mActivities.add(activity); } public void unRigistActivity(Activity activity) { mActivities.remove(activity); }}
The onCreate and onDestroy methods of MainActivity respectively call the registActivity and registActivity methods for registration and anti-registration. However, the OtherActivity only registers, but forgets the anti-registration function.
Public class MainActivity extends Activity {public static final String TAG = MainActivity. class. getSimpleName (); private Button mBtn; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mBtn = (Button) findViewById (R. id. btn); mBtn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {Intent intent = new Intent (); intent. setClass (MainActivity. this, OtherActivity. class); startActivity (intent) ;}}); ActivityManager. instance (). registActivity (this) ;}@ Override protected void onDestroy () {super. onDestroy (); ActivityManager. instance (). registActivity (this);} public class OtherActivity extends Activity {public static final String TAG = OtherActivity. class. getSimpleName (); private Object [] mObjs = new Object [10000]; // simulate fast memory consumption to make the effect private Button mBtn; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_other); mBtn = (Button) findViewById (R. id. btn); mBtn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {for (int I = 0; I <mObjs. length; I ++) {mObjs [I] = new Object () ;}finish () ;}}); ActivityManager. instance (). registActivity (this) ;}@ Override protected void onDestroy () {super. onDestroy ();}}
In this case, the memory leakage is constructed by humans, so we already know the leakage in advance. However, in the actual development process, the memory leakage is hidden. We didn't know it at first, therefore, we need to test whether the APP has memory leakage by some means. Select the process to be tested in the Devices view, click the Update Heap button on the Device view panel, open the Heap view, and click Cause GC. Then, it repeatedly switches between MainActivyt and OtherActivity. Observe the Heap size changes. You will find that the memory is constantly increasing. There is no stable trend. At this time, you have reason to suspect that the memory has leaked.
Update heap to observe heap size and other changes
Find the leaked object
According to the above mat usage steps, dump a memory snapshot and click "Leak suspects" in the Analysis Report. This will expose objects that may be leaked by the train. You will find "com. vjson. leaks. otherActivity. The OtherActivity class has 33 instances. As the code producer, you should suddenly find that the OtherActivity leaked. How can I find out which object holds the reference of the OtherActivity object after it is leaked?
Reports that may leak
Locate the reference chain
When I use the OQL object query language to query the leaked objects, I am familiar with SQL statements, which are similar to SQL statements and easy to understand, but very powerful select * from com. vjson. leaks. in the OtherActivity competition, OtherActivity is selected, and then "exclude weak/soft references" is selected to select objects other than soft references and weak references, that is, strong references !. The object reference type is not in the scope of this article, but you must know "strong reference", "soft reference", and "weak reference ". "Ghost reference". If you do not know how to make up your mind!
OQL object query to find the reference chain
Object Reference chain
Then find the root node of GC. From figure 2, we can see that the original Activity object is held by the ArrayList in ActivityManager, so the next task is to re-register it in onDestroy of OtherActivity, memory leakage is solved.
In Android development, common memory leakage objects are not unregistered. The database cursor is not closed. Bitmap is not recycled. ListView item is not reused. Handler is defined as a non-static anonymous internal class summary in Activity.
If you have read this article patiently, congratulations, mom will no longer have to worry about memory leaks. In fact, as long as you master the skills and tools for problem analysis, the memory leakage is so easy. The article briefly introduces the tools and skills, and many of them need to be explored by yourself.