Posterous theme by Cory Watilo

Android Memory Management

Android Dalvik VM has a garbage collector, which works pretty well, but the problem is garbage collection does not ensures memory leak. As telephones have low memory, and android have a great variety of devices which have a greater or smaller memory, you should be so much carefull about memory management.

Memory

The biggest problem occurs when you play with big files like images. Images are not stored as byte array and not stored in VM heap space. But your applications overall memory is calculated by adding this extra storege that are used for images(or other media) and heap space. You should not exceed 4 MB. Memory leak is easier than you think while garbage collection is on. Let me explain.

  TextView textView = new TextView(this);
  textView.setBackgroundDrawable(getDrawable(R.drawable.your_image));  
  setContentView(textView);

This code seems so innocent but it is not. As you are binding a drawable object (which consumes too much space on memory) to a textView, and afterwards you are binding this textView to your Activity object (which is alive till your application kills). As there exists a reference to all of these objects garbage collector can not release these objects. And your application crashes by operating system when it exceeds and have much  limits.

Solution: I am collecting all the images in a arrayList and when it is not visible to the user I set all drawables callbacks to null and recycle drawable that can be leaked.

drawable.setCallback(null);
if(!((BitmapDrawable)drawable).getBitmap().isRecycled())
{
  ((BitmapDrawable)drawable).getBitmap().recycle();
}
drawable = null;

This code will remove all references that are connected to drawble. And garbage collector can work as expected. Otherwise you will have a outofmemory error and your application will be killed by operating system.

Anyway, you should be carefull as you are freeing an image from a view, you should handle situations that these null images are not shown to user. When user does an action like clicking back button or inflating that view, you should override and handle these situtions and generate new drawable objects. Creating new drawables will slow your application a little but it won't crash because of out of memory.

At last I want to say something about google maps on anroid. Google maps uses its own memory management system, and it won't consume your memory space. So be patient when memory consumption increases while playing with google maps.

You can use ddms tool under android_sdk/tools directory. To run it execute command ./ddms

Have fun of android development as it is pretty well designed but lacks of tools that iphone has. Anyway I like android as it is free.