Tropical Software Observations

26 July 2011

Posted by Anonymous

at 1:32 AM

3 comments

Coping with memory leaks in Android 3.0's ViewFlipper and Bitmap classes

Recently, I was baffled by a persistent memory leak in one of our company's Android 3.0 projects running on the Motorola Xoom. I spent a lot of time trying to figure out the source of the memory leaks without much luck.

After some digging around, I found a very helpful tool for the Eclipse IDE: MotoDev Studio, a free plugin provided by Motorola for Eclipse. You can download it here: http://developer.motorola.com/docstools/motodevstudio/

After a cursory look, one might think that this is simply an IDE helper for Android/Xoom development. It is, but it also makes Android/Xoom development much easier.

The plugin provides a tool called Memory Analyzer Tool (MAT) that generates memory usage reports; if you run this while debugging your Android apps, it gives you a full report on memory usage.

For my project, the Memory Leaks report showed that memory leaks were coming from two Android classes: ViewFlipper and Bitmap.

I couldn't find any easy fix for ViewFlipper; the only solution I could think of was to completely remove the ViewFlipper and write my own custom handler to do the view switches. This was annoying, but fixed the memory leak.

For Bitmaps, there were several things I learned in order to repair the memory leaks:

1. ImageView: do not bind images by using "android:src", use ImageView.setImageResource() instead.
2. View Switch: if you have many ImageView objects being switched in and out, remove them all and only use one inside your code; remove the ImageView object when you switch to another kind of View, then add it again when you need ImageView again.
3. Use the willNotCache() method in ImageView.
4. Remember to set bitmaps to null or release them when finished using them, then push them to the GC.

There are still a lot of things you need to be careful of when using bitmaps, but in sum: remember to always release the memory used for the bitmaps when it's no longer needed.

After 3 days work, and I successfully reduced the memory use for our app from 40MB to 8.7 MB.

- Winkey