Mr.Drew
Mr.Drew

Reputation: 1079

What is the difference between `finishAffinity();` and `finish()` methods in Android?

I've using some code for a sign in screen that forces the app to close if the user doesn't want to sign in. If the user chooses to not sign in/cancel, it calls the code to exit the app. I've successfully done this two ways (not at the same time) with:

finishAffinity();
 System.exit(0);

and

finish();
 System.exit(0);

Yet both lines of code seem to do the same thing... The app is closed to the user, yet remains in the background apps to be reopen if the user hits the 'overview' button they can select it to reopen. (Which just restarts the prompt to sign in.)

Since I notice no functional difference, I'm wondering what is the difference between finishAffinity() and finish() methods?

Bonus Question: Also, is there a way to completely shut down the app, so it also doesn't appear in the overview button app list?

Upvotes: 22

Views: 31644

Answers (3)

Zahoor Saleem
Zahoor Saleem

Reputation: 634

finishAndRemoveTask() method pop out all your activities from stack and removes the application from recent task list simple finish this current activity as well as all activities immediately below it in the current task that have the same affinity, finish() method pop out your current activity from stack. for detail document link

finishAffinity(): finish the current activity and all activities immediately below it in the current task that have the same affinity. finishAndRemoveTask(): call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Upvotes: 5

Abhinav Gupta
Abhinav Gupta

Reputation: 2265

finishAffinity() : finishAffinity() is not used to "shutdown an application". It is used to remove a number of Activities belonging to a specific application from the current task (which may contain Activities belonging to multiple applications).

Even if you finish all of the Activities in your application, the OS process hosting your app does not automatically go away (as it does when you call System.exit()). Android will eventually kill your process when it gets around to it. You have no control over this (and that is intentional).

finish() : When calling finish() in an activity, the method onDestroy() is executed this method can do things like:

  • Dismiss any dialogs the activity was managing.

  • Close any cursors the activity was managing.

  • Close any open search dialog.

Upvotes: 20

Ali Ahmed
Ali Ahmed

Reputation: 2178

finishAffinity():

Closes all the activities present in the current Stack

finish()

Closes only opened activity

Also, is there a way to completely shut down the app, so it also doesn't appear in the overview button app list?

Yes you can add android:noHistory="true" to your activities tag in the Manifest.xml for this pupose

Upvotes: 23

Related Questions