Memory Management For Android Apps (Google IO)
In gearing up for this year's Google IO, I started looking over all of the sessions from the last few years to see what kind of gems are hidden there. I recently watched the latest Google IO session on Memory Management within Android. While I watched the video, I took some notes of what I thought were the more important and interesting points. At a high level, the video has some interesting info about how memory is allocated in Android (and really, Java itself).
Garbage Collection (GC) is the process of reclaiming old memory in your application. Or in other words, taking objects that are no longer in use and freeing the memory used by them so the memory can be used for new objects.
The most interesting points in the video were about the Android Heap. The Heap is where all applications are stored within Android. Each Android app has a limit that is specific to each device. To find that limit, use the method ActivityMonitor,getMemoryClass.
Sometimes that Heap size isn't enough. Luckily, there is a way to increase the Heap size for your app. To increase the size, add the tag bigHeap to your Application tag in the manifest file. However, increasing the Heap can be a double-edged sword. By having a large Heap, GC can take considerably longer because GC has to go through a larger Heap to check for objects that can be freed. So just using this tag to get away from memory leaks in your app is a pretty bad idea and will only make your app performance decrease.
This video also goes into memory leaks. To start off, a memory leak means you still have a reference to an unused object, which means GC can't remove an object. One common memory leak in Android involves keeping a reference to an Activity(or a context) for far too long. This is especially common when handling Activity rotation changes. Finding and fixing memory leaks is more of a dark art of software development. It's a very important skill to have in your pocket simply because the Garbage Collector won't save your memory in all cases. For example, if you happen to pass Context objects around frequently in your application, it's much more likely that a memory leak has crept into your app. By using the Eclipse Memory Analyzer, it's pretty simple to find a leak using a few tricks that are shown in the video (like using Dominator Trees) and to do a few changes to your code to fix it.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)