Android Memory leak analysis combat

Source: Internet
Author: User

memory Leaks Simple introduction

Java ensures that objects are reclaimed by the garbage collector when no reference is directed to the object. The Java program Ape is a lot easier than the memory itself released by the C language itself. But it doesn't mean the Java program Ape doesn't 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 dynamically open space, after the completion of the use is not released, resulting in the occupation of the deposit element."

Until the end of the program. from the programmer's point of view, "memory leaks", in fact, is an object's life cycle beyond the programmer's expected length (call it "damn Not dead"!)

), 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 becomes very fast and gets stuck until the oom crashes . The next step is to use a case (a toy program designed to analyze memory leaks only). Do not imitate) to introduce the Memory leak analysis tool mat. And the techniques of memory analysis.

the public wants to be good. The first to profit the device

Prepare an analysis tool for memory leaks and be able to install the Eclipse plug-in mat. Assuming the Eclise installation mat is unsuccessful, it may be a lack of necessary libs. Suppose to find the library trouble, can just tick the second installation, but there will be a lack of certain functions, 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 to use the mat plugin

Assuming the installation is successful, the Mat tool is easy to use, first run the application that needs analysis, open Eclipse's devices view you will see click "Dump Hprof File" button, pay attention to click on it , Then wait (wait a few seconds) to dump a memory snapshot out, and then take the initiative to open the mat view, assuming that the mat is not installed successfully, will let you save a. hprof file to Local.

Look at the following illustrations.

Dump Hprof Start Mat tool

artificially creating a memory leak

Define yourself a activitymanager. Two methods are available to register and reverse the activity of the brochure. 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);}    }

In Mainactivity's OnCreate and OnDestroy respectively, the registactivity and Registactivity methods are called to register and reverse. But otheractivity is only a register. And forget the counter-register.

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 high-speed memory consumption.    Make 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 constructed artificially. So we already knew there was a leak, but the actual development process. Memory leaks are hidden, and we don't know it at first, so we need to measure whether the app has a memory leak. First select the process that needs testing in the devices view. Then click Update Heapbutton 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 added. 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

Dump a memory snapshot in accordance with the steps of the previous mat. Then click on "Leak suspects" from the analysis report, where the train may leak, and you will find the " com.vjson.leaks.OtherActivity" figure. Otheractivity There are 33 instances of this class. As a producer of code, you should suddenly find out 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

Using the 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, the syntax is easy to understand, but very powerful select *from com.vjson.leaks.OtherActivity Select the Otheractivity object, and then choose Exclude Weak/soft References "race selects objects other than soft and weak references, that is, strong references!. The reference type of the object is not in the scope of this article, but you must know the "strong reference", "soft reference". "Weak references". "Phantom quote", assuming you don't know what to do with your own brain!

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 in the counter-register , the memory leak is overcome.

memory leaks common in Android developmentobject does not have an anti-manualdatabase cursor not closedBitmap Not recycledListView Item is not re-usedHandler anonymous inner class defined in activity as non-staticSummary

Let's assume that this article is patiently read. Well, congratulations, your mom doesn't have to worry about memory leaks any more. In fact, only to master the analysis of the problem of skills and tools, memory leaks so easy. The article simply describes the tools and techniques. 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.