Like:
startActivity(intent);
finish();
Without calling finish() explicitly, onDestroy()
is not called for the former Activity, and I run out of memory (OutOfMemory Exception).
So, is it a good idea to call finish() explicitly to prevent OutOfMemory Exception?
When you start a new activity, the current activity is pushed onto the back stack of the current task. (You can change this behavior via flags and/or the manifest, but this is the default behavior.) When the user presses the back function, the top activity is finished and the stack is popped. The result is that the user sees the app return to the previous activity.
It's perfectly fine to call finish()
after starting a new activity. The result will be that the current activity (which is no longer at the top of the stack, since you just started a new one) will be removed from the stack. Then when the user presses Back, it will go to the previous activity on the back stack (or exit your app if the stack is empty).
If you are bouncing back and forth between, say, activities A and B by always starting a new one and never calling finish()
, this can cause an OOM exception as the stack fills up with instances of each activity.
You can read more about this in the guide topic Tasks and Back Stack. It also describes how to deal correctly with cycling between activities.
Doing this is fine if you don't need an instance of that Activity
. So when you press back on the next Activity
know that you won't come back to this one but whatever is on the stack below where that Activity
was or the home screen if there are no more.
However, I'm not sure this is why you are getting an OOM
exception and you should probably figure out where that is coming from instead. If you are using Bitmap
s then that could be causing the exception.