android – What is Activity.finish() method doing exactly?

android – What is Activity.finish() method doing exactly?

When calling finish() on an activity, the method onDestroy() is executed. This method can do things like:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog

Also, onDestroy() isnt a destructor. It doesnt actually destroy the object. Its just a method thats called based on a certain state. So your instance is still alive and very well* after the superclasss onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed

My 2 cents on @K_Anas answer.
I performed a simple test on finish() method.
Listed important callback methods in activity life cycle

  1. Calling finish() in onCreate(): onCreate() -> onDestroy()
  2. Calling finish() in onStart() : onCreate() -> onStart() -> onStop() -> onDestroy()
  3. Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

What I mean to say is that counterparts of the methods along with any methods in between are called when finish() is executed.

eg:

 onCreate() counter part is onDestroy()
 onStart() counter part is onStop()
 onPause() counter part is onResume()

android – What is Activity.finish() method doing exactly?

Also notice if you call finish() after an intent you cant go back to the previous activity with the back button

startActivity(intent);
finish();

Leave a Reply

Your email address will not be published.