I Found some codes for quit an Android application programatically. By calling any one of the following code in onDestroy() will it quit application entirely?
Since API 16 you can use the finishAffinity method, which seems to be pretty close to closing all related activities by its name and Javadoc description:
this.finishAffinity();
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and into its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
Since API 21 you can use a very similar command
finishAndRemoveTask();
Finishes all activities in this task and removes it from the recent tasks list.
getActivity().finish();
System.exit(0);
this is the best way to exit your app.!!!
The best solution for me.
Just to add one to the list of brutal methods of terminating an App:
Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);
You had better use finish()
if you are in Activity
, or getActivity().finish()
if you are in the Fragment
.
If you want to quit the app completely, then use:
getActivity().finish();
System.exit(0);
Similar to @MobileMateo, but in Kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
this.finishAffinity()
} else{
this.finish()
System.exit(0)
}
Is quitting an application frowned upon?. Go through this link. It answers your question. The system does the job of killing an application.
Suppose you have two activities A an B. You navigate from A to B. When you click back button your activity B is popped form the backstack and destroyed. Previous activity in back stack activity A takes focus.
You should leave it to the system to decide when to kill the application.
public void finish()
Call this when your activity is done and should be closed.
Suppose you have many activities. you can use Action bar. On click of home icon naviagate to MainActivity of your application. In MainActivity click back button to quit from the application.