Search code examples
androidmemory-managementback-stack

How to release memory when activity goes to stack?


My application consist (for example) of 3 activity: Activity1, Activity2, Activity3. Every activity has a unique background image on all its main layout declared in an XML File. From Activity1 user goes to Activity2 and next to Activity3 so first 2 get pushed into the stack. The problem is that first 2 activities occupy too much memory, and in Activity3 I have OOM exception sometimes. I have found this answer about reason of this behavior - https://stackoverflow.com/a/4836241/1159507 Before this, I believed that when activity goes to stack it releases all memory. I believe that the same behavior with fragments stack. So my question is - how to relese memory when activity or fragment goes to stack and keep responsible UI on back press?


Solution

  • Activity's resources (which are not released in onPause, onStop, ...) do not get released when the Activity goes to the background.

    • You can remove the background in onPause(), this way the GC will be able to destroy it. However, the "empty background" will be there for a fraction of a second. It is important to mention, you have to do this in onPause(). (I think changes after onPause (like changes in onStop) take effect when the Activity comes to the foreground, so the reference to the background would still be hold by the Activity while it is in the background.)
    • Other way is to call finish(), and manage the stack yourself. You would have to remember the starting Activity, and navigate to it manually when the user presses the back button.
    • And the last solution that pops into my mind is to make every Activity that contains huge resources a separate process by declaring the android:process attribute in the manifest. This way all of your Activities would have a separate full sized heap to use.