Saturday, June 30, 2012

Put persistent objects in the Application object in Android


The way objects can reference each other can lead to subtle memory leaks as discussed inthis Android document.  Objects that are used by Activities, for example static Class members, can end up making it impossible for the garbage collector to free the Activity since that Activity may be referenced by the object in a cyclic way.  For example, Drawables in Android have a callback reference to the widget in the Activity’s layout that it is tied to.  If the object is a memory hog you can end up leaking memory badly, especially if the Activity is tied to hordes of other memory consuming objects that are now unable to be freed.  Rather than try to analyze every object reference or Activity chain in your application, it is better to follow one simple rule of thumb religiously:
If you plan on keeping long-lived objects that need a context, remember the Application object.
The Application object is create only once in an Android application and persists through the application’s life cycle.  Put any objects that you want to persist, including those you don’t want reloaded every time a particular Activity starts due to excessive loading times, in the Application object and reference them through that class.

No comments:

Post a Comment