How to Analyze memory leakage in Android

Source: Internet
Author: User

Basic steps:

1. Use the ddms tool provided by eclipse to analyze the memory usage of each thread, as shown in

The heap View Interface is refreshed on a regular basis. You can see the changes in memory usage during constant operations on applications.

How can I determine whether the current process has memory leakage?

Note that the VM heap page contains a data object option in the middle, that is, the data object, that is, a large number of class objects in our program.

In a row of data object, there is a column named "total size", whose value is the total memory of all Java Data Objects in the current process. Generally, the size of this value determines whether memory leakage exists. Shows the selected row.

Based on this, we can determine that memory leakage exists:
1) continuously operate the current application or repeat an action. Observe the total size value of the data object.

2) under normal circumstances, the total size value will be stable within a limited range. That is to say, if the code logic in the program is good,

Objects that are not created are not normally recycled by the GC mechanism. Even if we continuously generate many objects, during the process of garbage collection by virtual machines, these objects are recycled normally, and the memory usage remains at a relatively stable level.

3) if the reference of an object is not released in the Code, the total size of the data object will not be significantly reduced after each GC, the total size value increases as the number of operations increases.
Under normal circumstances, the process of a virtual machine exists 64 M. If the memory leaks, heap size is constantly approaching 64 M. Once this value is reached, the application will be exited.
In the event of Memory leakage, the total size value is getting larger and larger. Press the "Dump hprof file" button and a prompt will be displayed to set the path for saving the hprof file. After saving, you can compare the log to analyze which operations cause memory leakage.

2. click the button to export
Use the MAT tool to analyze the hprof file. For detailed analysis steps and procedures, see the link below

Http://www.ibm.com/developerworks/cn/opensource/os-cn-ecl-ma/index.html

Eclipse installation address: http://download.eclipse.org/mat/1.3/update-site/

3. Open the MAT tool, File --> Open Heap Dump... select the hprof File you just saved to Open it.

An error may pop up, as shown in:

Tip: Unknown HPROF Version (java profile 1.0.3) (java. io. IOException)
Oh, don't think that the MAT tool version is incorrect. In fact, the hprof file of android needs to be converted here to open it with MAT. I don't know if Google is here.
What is it about optimization?
Use a tool in the tools directory of the android sdk for conversion.
4. Use AndrodiSDK/tools/hprof-conv to convert the hprof file,
First, go to your android sdk tools directory through the console
For example, hprof-conv input. hprof out. hprof

Use the MAT tool to open the converted hprof file and you will be able to see the complete memory usage analysis report. The main interface for MAT memory usage analysis is as follows:



Click Details to view the memory usage.

Tip1:

A better method is to capture an hprof file at the beginning of Memory leakage. When the memory leakage is very severe, the app will capture another hprof file when it is on the verge of crash.

By comparing the two charts, it is easy to see which of the above pie charts has memory leakage.

Sometimes it can be seen that there is another one. Then we will start with the analysis. Results can be obtained quickly.

Tip2:

View dominator_tree. You can analyze the most data items of data_object in the list, as shown in the following file (two items corresponding to and 80)

I have added a PhoneStateListener listener to onStart, but it is not set to null in onStop, resulting in Memory leakage.

Here is an example summarized by others:

Cause 1:

BraodcastReceiver, ContentObserver, FileObserver, and Cursor must be unregister or closed after the Activity onDeatory or a type of declaration cycle ends. Otherwise, the Activity class will be strongly referenced by the system and will not be recycled by the memory.

Cause 2:

Do not directly reference the Activity as a member variable. If you have to do so, use private WeakReference mActivity to do the same. For other objects such as services that have their own declared cycles, for direct reference, you must be cautious about the possibility of Memory leakage. ()

 
private static class MyHandler extends Handler {          private WeakReference<GeneralSettings> mStatus;            public MyHandler(GeneralSettings activity) {              mStatus = new WeakReference<GeneralSettings>(activity);          }            @Override          public void handleMessage(Message msg) {              GeneralSettings status = mStatus.get();              if (status == null) {                  return;              }                switch (msg.what) {                  case EVENT_UPDATE_STATS:                      status.updateTimes();                      sendEmptyMessageDelayed(EVENT_UPDATE_STATS, 1000);                      break;              }          }  }  

Cause 3:

The Context is referenced for a long life cycle.

private static Drawable sBackground;  @Override  protected void onCreate(Bundle state) {    super.onCreate(state);    TextView label = new TextView(this);    label.setText("Leaks are bad");    if (sBackground == null) {      sBackground = getDrawable(R.drawable.large_bitmap);    }    label.setBackgroundDrawable(sBackground);    setContentView(label);  }

The lifecycle of sBackground is longer than that of Activity. label references context, and sBackground sets label as an internal member variable. Therefore, sBackground references context. As a result, context cannot be released when activity ends, this causes memory leakage. (If you do not understand it, you need to study it carefully)

Finally, the author gives a summary (in some cases, I still don't know much about it ......)

Summary:

1. The reference to the activity should be controlled within the lifecycle of the activity;

2. If not, consider using getApplicationContext or getApplication;

3. do not use non-static external member variables (including context) in static variables or static internal classes, you should also consider setting the external member variable to null in a timely manner (in the above example, you can set the callback of sBackground to solve the memory leakage problem ); you can also use weak references in internal classes to reference variables of external classes;

4. release resources in onDestroy, such as clearing arrays directly referenced or indirectly referenced to images and other resources (using array. clear (); array = null );

Related Article

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.