Memory leakage analysis of Android applications

Source: Internet
Author: User

The Dalvik Virtual Machine supports garbage collection, but this does not mean you don't have to worry about memory management. Pay special attention to the memory usage of mobile devices. The memory space on the mobile devices is limited. In this article, let's take a look at how some of the memory profiling tools in the android SDK help us trim the memory usage of the application.

Some memory usage problems are obvious. For example, if the app has a memory leak every time the user touches the screen, the outofmemoryerror may be triggered and the program crashes. The other issues are subtle, but they may only reduce the performance of the application and the entire system (when the Garbage Collector runs at a high frequency and for a long time ).

Necessary tools:

The android SDK provides two main tools for analyzing the memory usage of applications: Allocation tracker and heap dumps in ddms. Allocation tracker is very useful, especially when you want to obtain a perceptual knowledge of the memory allocation of a program within a certain period of time. However, it cannot give you any information about the overall situation of the program heap. For more information about allocation tracker, see the article tracking.
Memory allocations. The rest of the article will focus on heap dumps, which is a more powerful memory analysis tool.


A heap dump is a heap snapshot, Which is saved as a binary format called hprof. Dalvik uses a similar format, but not exactly the same. Here is the hprof tool of Java. There are many ways to generate a heap dump of the runtime application. One of them is to use the dump hprof file button in ddms. To generate more precise dump data, you can use the Android. OS. Debug. dumphprofdata () method in the program.

To analyze heap dump, you can use some standard tools such as jhat or eclipse memory analyzer (MAT ). However, first you need to convert the. hprof file from Dalvik format to j2se
Hprof format. You can use the hprof-Conv tool provided by the android SDK. For example:

  1. Hprof-Conv dump. hprof converted-dump.hprof

Debug a memory leak instance:


During Dalvik running, programmers cannot explicitly allocate and release the memory, so the memory leakage here is different from that in C and C ++. In your code, memory leakage is a reference to a class object that you no longer need. Sometimes a single reference will impede GC's collection of a large number of objects.

Let's take a practical example. The example app honeycomb gallery sample app provided in the android SDK. It is a Photo Gallery program used to demonstrate the use of some new honeycomb APIs. (For more information about downloading and compiling these codes, see these commands .) We will intentionally Add a memory leak to the program and then demonstrate how to debug it.

 
Imagine that we want to modify the program so that it can download images from the network. To make it more flexible, we can consider implementing a cache to save recently viewed images. We can make some minor modifications to contentfragment. Java to achieve this goal. At the top of the class, we add a new static variable:

  1. Private Static hashmap <string, bitmap> sbitmapcache = new hashmap <string, bitmap> ();

This is where we save the cache. Now we can modify the updatecontentandrecyclebitmap () method to check whether the data already exists before downloading it. If not, download the data and add the data to the cache.

  1. Void updatecontentandrecyclebitmap (INT category, int position ){
  2. If (mcurrentactionmode! = NULL ){
  3. Mcurrentactionmode. Finish ();
  4. }
  5. // Get the bitmap that needs to be drawn and update the imageview.
  6. // Check if the bitmap is already in the cache
  7. String bitmapid = "" + category + "." + position;
  8. Mbitmap = sbitmapcache. Get (bitmapid );
  9. If (mbitmap = NULL ){
  10. // It's not in the cache, So load the bitmap and add it to the cache.
  11. // Danger! We add items to this cache without ever removing any.
  12. Mbitmap = directory. getcategory (Category). getentry (position)
  13. . Getbitmap (getresources ());
  14. Sbitmapcache. Put (bitmapid, mbitmap );
  15. }
  16. (Imageview) getview (). findviewbyid (R. Id. Image). setimagebitmap (mbitmap );
  17. }

I have already intentionally introduced a memory leak problem here: we added images to the cache but never removed them. In real applications, we can use some method to limit the cache size.

 

Check heap usage in ddms

 

Dalvik debug monitor server (ddms) is one of the main Android debugging tools and is part of ADT Eclipse plug-in, the independent program version can also be found under tools/in the root directory of the android SDK. For more information about ddms, see use ddms.

 

We will use ddms to check the heap usage of this application. You can use the following two methods to start ddms:

  • From Eclipse: ClickWindow> open perspective> other...> ddms
  • Or from the command line: Run ddms (or./ddms on MAC/Linux) in the tools/directory

 

On the left-side pane, select com. example. Android. hcgallery and Click Show heap updates in the toolbar. Switch to the VM heap page of ddms. It displays some basic data of heap memory after each GC. To view the data content after the first GC, click the cause GC button:

 

 

We can see that the current value (allocated column) is more than 8 Mb. Now, move the photo to see that the data is increasing. Because only 13 photos are in the program, the leaked memory is only that large. To some extent, this is the worst type of Memory leakage, because we cannot get outofmemoryerror to remind us that the memory has exceeded.

 

Generate heap dump

 

We now use heap dump to track this issue. Click the dump hprof file button on the ddms toolbar, select the file storage location, and then run hprof-Conv. In this example, we use an independent mat version (version 1.0.1) to download it from the mat site.

 

If you use ADT (which includes the ddms plug-in) and install mat in eclipse, click "Dump hprof" to automatically perform the conversion (using hprof-Conv) at the same time, the converted hprof file will be opened in eclipse (it is actually opened with Mat ).

 

Use mat to analyze heap dumps

Start mat and load the hprof file we just generated. MAT is a powerful tool that describes all its features beyond the scope of this article, so I just want to demonstrate a method you can use to detect leaks: histogram view. It displays a list of sortable class instances, including: shallow heap (total memory usage of all instances) or retained heap (total memory allocated to all class instances, including all the referenced objects ).

 

If we sort by shallow heap, we can see that the byte [] instance is at the top. Since android3.0 (honeycomb), the pixel data of bitmap is stored in the byte array (previously stored in the heap of Dalvik). Therefore, it is determined based on the size of this object, needless to say, it must be our leaked bitmap.

 

Right-click the byte [] class and select list objects> with incoming references. It will generate a list of all the byte arrays on the heap. In the list, we can sort by shallow heap usage.

 

Select and expand a large object, which will display the path from the root to this object-is a chain that ensures the object is valid. Note that this is our bitmap cache!

 

Mat won't tell us clearly that this is a leak because it doesn't know whether the program needs this thing or not. Only the programmer knows it. In this case, the large amount of memory used by the cache will affect the subsequent applications, so we can consider limiting the cache size.

 

Use mat to compare heap dumps

 

When debugging memory leaks, it is sometimes useful to compare the heap status in two places in a timely manner. In this case, you need to generate two separate hprof files (do not forget the conversion format ). The following is some information about how to compare two heap dumps in mat (a little complicated ):

  1. The first hprof file (usingFile> open heap dump).
  2. Open histogram view.
  3. In the navigation history view.Window> navigation history), Right-clickHistogramThen selectAdd to compare basket.
  4. Open the second hprof file and redo steps 2 and 3.
  5. Switch to the Compare basket view and clickCompare the results(Red in the upper-right corner of the View "! "Icon ).

Summary

This article shows how allocation tracker and heap dumps give you a perceptual knowledge of program memory usage. I also showed that eclipse memory analyzer (MAT) can help chase memory leaks in our programs. MAT is a powerful tool, and I just touched some skins. If you want to learn more, I suggest reading the following articles:

  • Memory analyzer news: the official blog of the eclipse mat project.
  • Markus Kohler's Java performance blog has many useful articles, including the analysis of the memory usage of Android applications
    The eclipse memory analyzer and 10 useful tips for the eclipse memory analyzer.

    Memory Analysis of Android applications
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.