I have an Android Honeycomb application with two activities; the first one has a large Bitmap (taken from resources) as a background to the main LinearLayout and I have discovered that setting the background of this element to null from the activity’s onStop() method can save a lot of memory—around 5MB, in fact.
However, this only seems to work when I click the “sleep” button on the device. If I do that the profiler shows the 5MB drops out of the world as easy as you like. If I start the second activity, the first activity’s onStop() doesn’t get hit until after the second activity’s onCreate() and the profiler suggests that the BitmapDrawable is not removed from memory after all—so there it sits, five invisible useless megabytes, cluttering the place up.
I could remove this from onPause(), which might work better, but I’m also using the onStop() methods of various Dialog elements to null their background drawables as well. They don’t seem to have onPause() methods.
Is there a recommended method for getting rid of these kinds of large, memory-consuming elements as an activity launches another one?
Also for me OnPause event is a better place where put your “memory-free” code.
Here the event flow when you open a child activity from a parent activity
As you already noticed, parent’s onStop is called only after complete child creation.
What about calling memory-free code from two different location? Consider that dialogs, generally, don’t completely cover calling activity, so preserving it’s background has a sense.
Maybe a flag can be set when you open a new activity instead of a dialog, and OnPause logic will drop background only when a new activity is launched, and not a dialog.