Android Memory leak analysis combat

Source: Internet
Author: User

Introduction to memory leaks

Java can guarantee that when there is no reference to the object, the object will be reclaimed by the garbage collector, compared to the C language's own application of the memory itself, the Java programmer is much easier, but does not mean that the Java programmer does not have to worry about memory leaks. When a memory leak occurs in a Java program, it is often hidden. Therefore, the use of some professional platform Resources to ensure security, such as can be achieved through encryption .

definition

Quote Baidu Encyclopedia definition: "Dynamic storage allocation function to open up the space, after the use has not been released, resulting in the result has been occupied in the memory element." Until the end of the program. from the point of view of a program ape, a "memory leak" is actually an object whose life span is beyond the programmer's expected length (call it "damn it!"). ), then the object is leaked.

memory leaks in Android development

The Android application itself has very little memory allocated, and once a leak occurs, the program quickly becomes very stuck until the oom crashes . The next step is to introduce the memory leak analysis tool mat, as well as the techniques for memory analysis, through a case (a toy program designed to analyze memory leaks only, not to imitate).

The public wants to be good, the first to benefit the device

Prepare the memory Leak analysis tool to install the Eclipse plug-in mat. If the Eclise installation mat is unsuccessful, it may be a lack of necessary libs, if you are looking for a library trouble, you can only check the second installation, but will be missing some features, but also enough.
Online installation:http://download.eclipse.org/mat/1.4/update-site/
Download install:http://mirror.hust.edu.cn/eclipse//mat/1.4/MemoryAnalyzer-1.4.0.201406041413.zip

how the Mat plugin is used

If you have successfully installed the Mat tool, it is very simple to use, first run the application that needs analysis, open the Eclipse devices view you will see click "Dump Hprof File" button, pay attention to click on it , Then wait (wait a few seconds) dump a memory snapshot out, then automatically open the Mat view, if the mat is not installed successfully, will let you save a. hprof file to Local. Look at the legend below.

Dump Hprof Start Mat tool

artificially creating a memory leak

Customize a Activitymanager, which provides two methods for registering and registering the activity with each other. Source Download

public class Activitymanager {
   private list<activity> mactivities = new arraylist<> ();
    private static Activitymanager sinstance;

   private Activitymanager () {
   };

   public Static Activitymanager instance () {
       if (sinstance = = null) {
& nbsp          sinstance = new Activitymanager ();
       }

       return sinstance;
   

   public void registactivity ( Activity activity) {
       mactivities.add (activity);
   }

    public void unrigistactivity (activity activity) {
       mactivities.remove (activity);
   }
}

The Registactivity and Registactivity methods are called in Mainactivity OnCreate and OnDestroy respectively for registration and anti-registration. But otheractivity just register, and forget the anti-registration.

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];//simulates fast memory consumption, making the effect obvious
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 ();
}
}

The memory leaks in the case are artificially constructed, so we already knew there was a leak, but the actual development process, the memory leak is hidden, at first we do not know, so we need to use some means to test whether the app has a memory leak. First select the process you want to test in the Devices view, then click the Update Heap button in the Device View panel, then open the heap view and click Cause GC. Then switch between Mainactivyt and Otheractivity repeatedly. Observe the changes in the heap size. You will find that the memory has been increasing. There is no steady trend. At this point you have reason to suspect a memory leak .

Update Heap to observe changes in heap size, etc.

find the Leaking object

Follow the previous Mat usage steps, dump a memory snapshot out, and then click "Leak suspects" from the analysis report here will train may leak objects, where you will find " com.vjson.leaks.OtherActivity" The figure. Otheractivity This class has 33 instances, as the code of the producer, you should suddenly find that the original is otheractivity leaked. After discovering it leaks, how do you find out which object holds a reference to the Otheractivity object?

Reports that could leak

Find the reference chain

use OQL object Query language to query out the leaking object, the classmate who wrote SQL Must have a strange and familiar feeling to her, very similar to SQL, easy to understand grammar, but very powerful select *from Com.vjson.leaks.OtherActivity selected objects of Otheractivity, and then chose "Exclude Weak/soft References" to elect objects other than soft and weak references. That's a strong quote!. Object reference type is not covered in this article, but you must know "strong reference", "soft reference", "weak reference". "Ghost Quote", if you do not know your own brain to repair it!

OQL Object query Find reference chain

Object reference Chain

Then find the GC root node, from figure two can be seen, the original activity object was Activitymanager inside the ArrayList to hold, so the next job is in otheractivity OnDestroy anti-registration, The memory leak is resolved.

memory leaks common in Android development object has no anti-registration database cursor not closed Bitmap Not recycled ListView Item is not re-used Handler anonymous inner class defined in activity as non-static Summary

If you read this article patiently, then congratulations to your mother no longer have to worry about memory leaks. In fact, as long as mastered the analysis of the problem of skills and tools, memory leaks so easy. The article simply introduces the tools and techniques, and there are a lot of tricks that need to be explored.


Android Memory leak analysis combat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.