What Android tools and methods work best to find memory/resource leaks? [closed]
I've got an Android app developed, and I'm at the point of a phone app development where everything seems to be working well and you want to declare victory and ship, but you know there just have to be some memory and resource leaks in there; and there's only 16mb of heap on the Android and its apparently surprisingly easy to leak in an Android app.
I've been looking around and so far have only been able to dig up info on 'hprof' and 'traceview' and neither gets a lot of favorable reviews.
What tools or methods have you come across or developed and care to share maybe in an OS project?
Solution 1:
One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frecuently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory avaiable for bitmaps.
Bitmaps on the previous activity layout are not properly deallocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.
First, set the “id” attribute on the parent view of your XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/RootView"
>
...
Then, on the onDestroy() method of your Activity, call the unbindDrawables() method passing a refence to the parent View and then do a System.gc()
@Override
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.RootView));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
This unbindDrawables() method explores the view tree recursively and:
- Removes callbacks on all the background drawables
- Removes childs on every viewgroup
Solution 2:
Get the Eclipse Memory Analyzer ( http://www.eclipse.org/mat/) Check http://kohlerm.blogspot.com/2010/02/android-memory-usage-analysis-slides.html and http://kohlerm.blogspot.com/search/label/memory
Solution 3:
Mostly for Google travelers from the future:
Most java tools are unfortunately unsuitable for this task, because they only analyze the JVM-Heap. Every Android Application also has a native heap, though, which also has to fit within the ~16 MB limit. It's usually used for bitmap data, for example. So you can run quite easily into Out Of Memory errors even though your JVM-Heap is chillin around 3 MBs, if you use a lot of drawables.