How to analyze memory leaks in Android

Source: Internet
Author: User

Prerequisites:

1, the computer installed the Java operating environment

2, USB debug switch on the phone

3, Get root permissions

4, installing the Mat tool,: http://www.eclipse.org/mat/downloads.php

Basic steps:

1, use the Eclipse-DDMS tool to analyze the memory usage of each thread, as shown in

The heap view interface is refreshed periodically, and changes in memory usage can be seen during the ongoing operation of the application.

How can I tell if there is a memory leak in the current process?

Here's a value: There is a data object option in the middle of the VM heap page, which is an object of a large number of class types in our program.

In the data object row, there is a column "total size", whose value is the amount of memory for all Java data Objects in the current process, in general, the size of this value determines whether there is a memory leak. As shown in the selected row.

A memory leak can be judged as follows:
1) constantly manipulate the current application, or repeat an action, and watch the total size value of the data object.

2) Under normal circumstances the total size value will stabilize in a limited range, that is, if the code in the program logic is good,

Objects that are not created are not properly recycled by the GC mechanism, and even though we continue to generate many objects, these objects are normally recycled while the virtual machines are being garbage collected, and memory usage is maintained at a fairly stable level.

3) If there is no release of the object reference in the code, the total size value of data object will not come down significantly after each GC, and the value of total size will increase as the number of operations increases.
Normally, the memory of a virtual machine's process is 64M, and if a memory leak finds that the Heap Size is constantly approaching 64M, the exit application will appear once this value is reached.


When a memory leak occurs, the value of total size is getting larger, press the "Dump HPROF File" button, this time will prompt to set the HPROF file save path. After saving, you can compare log to analyze what is causing a memory leak.

2. Click the button to export the Hprof file and analyze it using the mat tool. Detailed analysis steps and procedures are described in the following links

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

3. Open the MAT tool, File-->open Heap Dump ... Select the Hprof file you just saved to open

At this point, an error pops up, as shown in:

Tip: Unknown HPROF Version (JAVA profile 1.0.3) (java.io.IOException)

Oh, do not think it is the mat tool version is wrong, is actually Android Hprof file here need to convert the format can use MAT Open, do not know Google here

What the heck, is it optimized?

Use one of the tools in the Android SDK directory to convert

4, using Androdisdk/tools/hprof-conv to convert hprof files,

First, go to your Android SDK Tools directory via the console

For example Hprof-conv input.hprof out.hprof

Using the Mat tool to open the converted Hprof file, you can see the full Memory Usage Analysis report.

The main interface used by the MAT analysis memory is as follows:

Click on the Reports-->leak Suspects to see more detailed memory leak suspects.

Where you suspect, click Details to see the specific memory usage.

TIP1:

A good way to do this is to crawl a hprof file when the memory leak starts, and when the memory leak is bad, the app is on the verge of crashing and crawls a hprof file.

Looking at these two graphs, it's easy to see which of the above pie charts has a memory leak.

Sometimes I can see it more directly. So let's start with that piece of analysis. It's quicker to get results.

TIP2:

See Dominator_tree, you can data_object the most data from the list to start analysis, as shown in the following file (136,80 corresponding two)

I've been on this side since I added a Phonestatelistener listener in OnStart, and the onStop is not set to NULL, causing a memory leak.

Summary one:

Cause 1:

Braodcastreceiver,contentobserver,fileobserver,cursor must be unregister or close after the activity ondeatory or the end of a certain class of declaration period, Otherwise, the activity class will be strongly referenced by the system and will not be reclaimed by memory.

Cause 2:

Do not directly refer to the activity as a member variable, if you have to do so, please use private weakreference mactivity to do, the same, for the service and other objects with their own life cycle, Direct referencing requires careful consideration of possible memory leaks.

[Java]View PlainCopy
  1. Private static class MyHandler extends Handler {
  2. private weakreference<generalsettings> Mstatus;
  3. Public MyHandler (generalsettings activity) {
  4. Mstatus = New weakreference<generalsettings> (activity);
  5. }
  6. @Override
  7. public void Handlemessage (Message msg) {
  8. Generalsettings status = Mstatus.get ();
  9. if (status = = null) {
  10. return;
  11. }
  12. switch (msg.what) {
  13. Case Event_update_stats:
  14. Status.updatetimes ();
  15. Sendemptymessagedelayed (Event_update_stats, 1000);
  16. Break ;
  17. }
  18. }
  19. }

Cause 3:

Maintains a reference to the Context for a long life cycle.

[Java]View PlainCopy
  1. Private static drawable Sbackground;
  2. @Override
  3. protected void OnCreate (Bundle state) {
  4. super.oncreate (state);
  5. TextView label = new TextView (this);
  6. Label.settext ("Leaks is bad");
  7. if (sbackground = = null) {
  8. Sbackground = getdrawable (R.drawable.large_bitmap);
  9. }
  10. Label.setbackgrounddrawable (Sbackground);
  11. Setcontentview (label);
  12. }


The life cycle of the sbackground is longer than the activity, and the label refers to the Context,sbackground and sets the label as an internal member variable, so sbackground refers to the context, The context is still not released when the activity ends, causing a memory leak. (Not very understanding, but also to study carefully)

Finally, the author gives a little summary (some places still don't understand ...). )

Summary two:

1. References to activity should be controlled within the life cycle of the activity;

2. If it is not possible to consider using Getapplicationcontext or getapplication;

3. Try not to use non-static external member variables (including context) in static variables or static internal classes, even if they are to be used, consider emptying the external member variable as appropriate (as in the example above can solve the problem of memory leak by Sbackground the callback empty) ; You can also use weak references in inner classes to refer to variables of external classes;

4. To release resources in OnDestroy, such as emptying an array with direct or indirect references to resources such as images (using array.clear (); array = null);

5. Threads must be managed well, many of the memory leaks encountered in development are due to the fact that threads are not shutting down in a timely manner, and each operation is re-created by this thread;

6. Use static variables with caution, some temporary classes using static variables can easily cause such objects to be unable to release and thus cause memory leaks;

How to analyze memory leaks in Android

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.