Hunting YOUR leaks:memory MANAGEMENT in ANDROID (Part 2 of 2)

Source: Internet
Author: User

Woo-hoo! Now you know what's happening with your app's memory usage when you see one of the those OOM exception. But, you don ' t know where to find the source. Let's alone, how to fix it.

Tracking down memory issues can is a pain in the neck. Here is a few strategies that'll help you pursue the noble craft of Android-igami.

Sample Project

There is code snippets and screenshots of what I ' m working on sprinkled throughout this post. These'll come from a single sample project, and if you prefer to see things in their entirety before being divided into Little pieces, I provided that the sample project to download here.

    • Yes, it uses Eclipse. Sorry to all cutting edge folks working with the still beta Android Studio.
    • Structure:one activity, with a fragment. You'll see a image that turns on and off every 5 seconds.
    • We ' re using a singleton manager to keep time for us, and notify the Fragment when it's time to switch the image is on or off.

For those keeping score @ Home, this project have one a-level memory leak:the type of leak that no developer should ever Allow into their code. And I ' m not a going to the where it is. But, that's the purpose of this experiment! So let's take a look at where it goes wrong.

Examination 1: "UPDATE HEAP" button

    1. Open the DDMS1 perspective in Eclipse (It should is found somewhere around the Window->Open Perspective->Other popup dialog).
    2. Highlight the process you wish to profiles (most real devices would only show "debug"-signed processes, so you're only see it On a real device if you built and installed from adb ).
    3. Tap the little Green "disk" icon (circled in above image), named "Update Heap."
    4. Make sure your open the Heap panel on the ' right side ' of the screen.
    5. Tap the "Cause GC" button2.

This would put some numbers in the that chart. The one we should focus on are "allocated," which shows you how much memory the Dalvik VMS currently has given your app. Thi s can stretch and shrink a bit, but there's a upper limit (the size of which depends on the device). If you exceed the upper limit, you are pop out of an OOM and the app crashes.

This was a great tool to keep a in the while develop, since it shows a live snapshot of the system after any garbage C Ollection cycle. If you ever notice the allocated memory gradually increasing without ever letting anything go, that ' s a good indication th At you might has a memory leak. 3

Examination 2:mat & HPROF-A.K.A, "The HUNT"

There is some acronyms for you, huh?

"MAT," the Eclipse Memory Analyzer tool, can read a file that your Vsan generates (Remember that onewe tal Ked on the Last post? It ' s called Dalvik). That file, called a "heap dump," represents the set of any objects currently stored on your process ' s heap4. That's means you can actually poke around the metadata of the objects you ' re using during runtime.

What are you ' ll need:

    • Eclipse (the Google provided "ADT" version works well here).
    • MAT.
    • If you're not using the DDMS plugin, you'll need to manually convert the Dalvik profiles into a .hprof file.
Plot a Course

Run the Memoryleek project on an emulator5. You should see a white screens with a slowly blinking image. Rotate the emulator ten or so times (either on the 7 numpad or Cntrl + F12 ). Now, return to Eclipse, and open the DDMS perspective once again. This time, we ' re aiming for the green disc icon with an arrow attached-indicating you want to generate a heap dump. Go ahead and click it, and you should see a statement in the Android log that looks like:

Java
1 I/DALVIKVM (1948): Hprof:dumping Heap strings to "[DDMS]".

That ' s good. Now leave it-a bit, because it could take a couple of minutes to generate (and the emulator are frozen until it finishe s).

Once the output is ready, it should prompt your about some different types of reports. (If you instead see a prompt to save a file, go ahead and save it somewhere, then use the SDK tool Hprof-conv to convert I T to the appropriate format, and manually open it with Eclipse ' s MAT). Once You has the "reports" prompt, just cancel out of the It-we ' re not going to use any pre-set reports for this.

Load your Ammo

hooray! If You're reading this, you're hopefully looking at some kind of graph of the Your app ' s current memory state. In my case, a pie chart.

What is now?

Let ' s try poking around a bit. Click the Little bar chart icon in the top left, that says "Create a histogram ..." when you hover over it. This would show you a list of all the objects currently allocated and in no particular order.

You ' re looking at the name and package of the objects in the first column, the number of this kind of object in existence At the moment in the next column and then some representation of the total heap sizes in the third and fourth columns6 .

It might be interesting to sort by size or count to see where the majority of memory are being used in your code7. If you right-click on one of the these listings, you can get the some cool options, like all instances of the objects of that type wit H all the references this keep it from being garbage collected.

But wait, we're supposed to being hunting for something, right? We need a target of some kind.

Tracking the game

There ' s a lot of noise in an app's memory space. Fortunately, we can narrow it down in a few ways.

First, try applying filtering to this list. In the first row, you can enter text. Since almost always want-a closer look at your code, I suggest entering something like "Com.example.memorylee K ". This should filter down to a handful of entries.

Gazing upon these, I ' m hoping you notice something horrifying. If you don ' t, I recommend taking another look at part 1 of the This series. Hopefully you'll figure out what's the worst thing in the world to leak would is.

Hint:it ' s activities.

And, good Lord, I had instances of leekactivity right now! That ' s totally is not OK.

Why might this is?

Well, kindly, the MAT has a-to-tell us. You can right-click this list item, and select "Merge shortest Paths to GC Roots", excluding weakreferences (remember, Wea Kreferences'll has no effect on what's retained). This means we want to see what the memory root all these objects has in common. That should indicate if there's something retaining all of the them at once, ergo, a leak of some kind!

In the case, there is 3 roots. The them is external to this project, so aren ' t likely culprits. But, that Leekmanager instance looks suspicious ....

a-ha! If you open it up and you can see that there's a linkedlist called "listeners" on the Leekmanager that have a reference to all of Those activities.

But, where do you come from?

Well, check this out:

 //  in Leekfragment.class:   @Override  public  void   OnCreate (Bundle savedinstancestate) { super  .oncreate (savedinstancestate);  //  Add this fragment as a leek listener so 
    //  It can update its view accordingly  Leekmanager.get (). AddListener (this   

Every time LeekFragment we are created, we add it as a to the LeekListener LeekManager Singleton. But, when we do those rotations, the Fragment was never removed as a listener. The Fragment have a reference to the parent Activity, and the parent have references to all of the other LeekActivity view elements.

Taking the shot

There ' s our leak. Fixing it? Easy: LeekFragment needs to is removed from LeekManager upon it onDestroy() lifecycle method.

Now, the above code looks like:

//In Leekfragment.class:@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //ADD This fragment as a leek listener so//It can update its view accordinglyLeekmanager.get (). AddListener ( This);} @Override Public voidOnDestroy () {Super. OnDestroy (); Leekmanager.get (). RemoveListener ( This);}

And when we run the app, we don't see any more indications of leaky memory! hoorah!

Hunting YOUR leaks:memory MANAGEMENT in ANDROID (Part 2 of 2)

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.