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?
On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.
As per official documentation: You can call finish() from within this function, in which case onDestroy() will be immediately called after onCreate(Bundle) without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.
Using activity. isFinishing() is the right one solution. it return true if activity is finished so before creating dialog check for the condition. if true then create and show dialog.
The onStop() and onDestroy() methods get called, and Android destroys the activity. A new activity is created in its place.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With