How to quit android application programmatically
Solution 1
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.
Solution 2
getActivity().finish();
System.exit(0);
this is the best way to exit your app.!!!
The best solution for me.
Solution 3
finishAffinity();
System.exit(0);
If you will use only finishAffinity();
without System.exit(0);
your application will quit but the allocated memory will still be in use by your phone, so... if you want a clean and really quit of an app, use both of them.
This is the simplest method and works anywhere, quit the app for real, you can have a lot of activity opened will still quitting all with no problem.
example on a button click
public void exitAppCLICK (View view) {
finishAffinity();
System.exit(0);
}
or if you want something nice, example with an alert dialog with 3 buttons YES NO and CANCEL
// alertdialog for exit the app
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set the title of the Alert Dialog
alertDialogBuilder.setTitle("your title");
// set dialog message
alertDialogBuilder
.setMessage("your message")
.setCancelable(false)
.setPositiveButton("YES"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// what to do if YES is tapped
finishAffinity();
System.exit(0);
}
})
.setNeutralButton("CANCEL"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// code to do on CANCEL tapped
dialog.cancel();
}
})
.setNegativeButton("NO"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// code to do on NO tapped
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Solution 4
Please think really hard about if you do need to kill the application: why not let the OS figure out where and when to free the resources?
Otherwise, if you're absolutely really sure, use
finish();
As a reaction to @dave appleton's comment: First thing read the big question/answer combo @gabriel posted: Is quitting an application frowned upon?
Now assuming we have that, the question here still has an answer, being that the code you need if you are doing anything with quitting is finish()
. Obviously you can have more than one activity etc etc, but that's not the point. Lets run by some of the use-cases
- You want to let the user quit everything because of memory usage and "not running in the background? Doubtfull. Let the user stop certain activities in the background, but let the OS kill any unneeded recourses.
- You want a user to not go to the previous activity of your app? Well, either configure it so it doesn't, or you need an extra option. If most of the time the back=previous-activity works, wouldn't the user just press home if he/she wants to do something else?
- If you need some sort of reset, you can find out if/how/etc your application was quit, and if your activity gets focus again you can take action on that, showing a fresh screen instead of restarting where you were.
So in the end, ofcourse, finish()
doesn't kill everthing, but it is still the tool you need I think. If there is a usecase for "kill all activities", I haven't found it yet.
Solution 5
Create a ExitActivity
and declare it in manifest. And call ExitActivity.exit(context)
for exiting app.
public class ExitActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
public static void exit(Context context) {
Intent intent = new Intent(context, ExitActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
}
Vignesh
Updated on January 04, 2021Comments
-
Vignesh over 3 years
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?
System.runFinalizersOnExit(true)
(OR)android.os.Process.killProcess(android.os.Process.myPid());
I dont want to run my application in background after clicking quit button. Pls suggest me can i use any one of these code to quit my app? If so which code can i use? Is it good way to quit the app in Android?
-
Tanner Perrien about 13 yearsCalling
finish()
will not kill the application.finish()
is used all the time:Call this when your activity is done and should be closed.
It's the same effect as hitting the "back" button. -
Nanne about 13 yearsFinish will kill the activity. how is this different then killing the appliation?
-
Tanner Perrien about 13 yearsThere is nothing wrong with "finishing" or "killing" the
Activity
(not theApplication
). For example, you might start a new activity to show the user some information. After a timeout or pressing 'OK' you might callfinish()
to return to the calling activity. -
CommonsWare about 13 yearsMost Android applications have more than one activity.
-
Nanne about 13 yearsSo you need to kill more then one activity, true, but the concept is the same, isn't it?
-
anonim about 12 yearssign out of an application requires to really kill the app. so there should be a way to ensure app killed after signing out
-
Dave Appleton almost 12 yearsNanne - if you have two activities, main and sub, main invokes sub. from sub you call finish - it closes sub and restores main. So the activity (sub) has been closed but the app is now showing main.
-
Jabari about 11 years@Nanne - A lock screen is an example of when you'd want to stop all activities. Suppose you log into a banking app. After a certain period of time with no interaction from the user, the lock screen launches. You'll want to stop all activities if someone hits the back button from the lock screen!
-
Sydwell about 10 yearsI total agree with this use-case. Also consider my secure app that must to be available in a certain location and should do it's best to close if the user is not at that location. What do I do?
-
Peter almost 10 yearsfinish it's not a way.. app steel running
-
mz87 almost 10 yearsyeah, works great! Have to call this from MainActivity to get it to work!
-
Romulus Urakagi Ts'ai over 9 yearsFinishing an Activity differs too much from terminating an Application with lots of Activities and Services. This is a bad answer.
-
Managarm over 9 yearsBy keeping a reference to your activity you are actually leaking memory! See this for an in-depth discussion.
-
Jabari over 9 years@Managarm The premise behind that post is that the static variable will remain even after the process (in this case, the Activity) has been destroyed. If proper house cleaning is done though, it's a non-issue...hence the reason I nullify the reference in the activity's onDestroy() method.
-
Managarm over 9 years@Jabari Ah, I missed the onDestroy part. In that case it should not be an issue, though it's not best practice.
-
Jabari over 9 years@Managarm I admit it relies on the programmer(s) to do their due diligence, and I fully understand how it can easily be looked over! That said, we should all be keeping such things in the back of our minds while coding. We should also heavily test for memory issues before deploying as well!
-
IAmTheSquidward over 9 yearsPerfect solution. No need to terminate the process, as Android knows best for memory management. However, this provides a solution for finishing the activity, as well as exiting the app for user convenience.
-
superuserdo over 9 yearsPerfect Solution really. Fixed a lot of problems. Thanks.
-
030 over 9 years
-
Antonio about 9 yearsDefinitely this is the right answer! It's not a good solution to finish an app using
System.exit(0);
. Thank you for your answer! Finally I've found a decent solution. -
Antonio about 9 yearsI don't think this is a good solution. You oughtn't finish your program using
System.exit(0);
. The right solution was posted by @sivi (his answer is above) -
user3290180 almost 9 yearsthis is not the solution, it doesn't work if you have a stack of activities
-
2Dee almost 9 yearsfinish() will close an Activity, but will certainly not close the entire app with certainty.
-
Script Kitty over 8 yearsDo you know if there is another solution on API 14? Thanks
-
sivi over 8 yearsYou can finish() each activity individualy, either when you close the app or inside the activity lifcycle.
-
LiangWang over 8 yearsas user3290180 pointed out, it's not a solution when you have multiple activities
-
Weiyi over 8 yearsClear all activities in the second app, and navigate back to the first app! Solve my problem ;-)
-
tryp about 8 yearsNice to know, thank you for the trick. It's better than the "raw" solution "System.exit(0);"
-
Laogeodritt almost 8 yearsThis quite the current Android component (e.g. activity), not the entire app.
-
Prashanth Debbadwar almost 8 yearsHi, can I do it in intent service(GcmListenerService)? The intent service will be called when pn comes.
-
Mr. Nobody almost 8 yearsworked without any problem. For
api>=16
usefinishAffinity()
else use this method. -
Tasneem over 7 yearsThis worked for me. I have tried such way if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getActivity().finishAffinity(); } else { System.exit(0); } But getActivity().finishAffinity(); is not clearing app data completely.
-
Tasneem over 7 yearsWhen I call getActivity().finishAffinity() , it does not call my Application class on clicking on the app icon while System.exit(0); does work.
-
Kumar Gaurav over 6 yearsThis will only send the app in the background
-
driftwood over 6 yearsthis is the correct answer, i was looking for. thanks
-
Tincho825 over 6 yearsWARNING! this.finishAffinity() closes app removing it from memory, so you wont receive push messages and so.
-
YellowJ about 6 years
finishAndRemoveTask()
did not work on Android N HTC One m9 device. It just finished the current activity.finishAffinity()
did. -
Slav about 6 yearsThis solution works 99% of cases. However, it will not destroy the process, so for example Dagger will not be cleared. In those rare cases, where killing the process is required,
System.exit(0)
is the only solution that worked for me. -
iOS-Coder almost 6 yearsThe finishAffinity() closes my app, but when I start it using a deeplink it however remains in the background. Anybody know how to stop a deeplink start app? The following codefragment however does not entirely stop my app (I've minSdk=19): public void onStopButton(View view) {this.finishAffinity(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); }
-
DoruChidean over 5 yearsThis is the most voted answer however it is a hack. Calling finish in onCreate will look glitchy on most, if not all, devices.
-
vivek over 5 yearsHmm its a hack but not a glitch. First exit() you will call, it comes at top of all activities with clear top and tasks then finish itself. here you EXIT.
-
Taslim Oseni over 5 yearsRemember to declare this class in your manifest. +1 for the clever hack though.
-
Heetola over 5 yearsthis is just freezing my app.
-
AxA over 5 yearsDoes this just bring home screen or actually kills the app?
-
ivan8m8 over 5 years
Process.killProcess(Process.myPid())
does the same, but is shorter -
Edgar Khimich almost 5 yearsIn addition to @Slav answer I can add that in using Koin you will also see this problem. Even when you use finishAndRemoveTask - it will still keep the instances in the memory after reopening the app. finishAffinity + System.exit(0) help me
-
Dragan Marjanović almost 5 yearsThis helped us make RetryRule works in our flakey connected tests.
-
roghayeh hosseini over 4 yearsif i used FCM , or background tasks in my app, I would have no problem?
-
Edgar Khimich over 4 years@Pulkit you are welcome man But just to let you know that it's not so good solution System.exit(0) i don't remember how I replace it cause it was on another project to which I don't have access any more. Sorry
-
kz_sergey over 4 yearsThis answer is not correct. Use finishAffinity(); System.exit(0);
-
A1m over 4 yearsThis was what I needed to wipe the application from memory
-
crgarridos about 4 yearsplease don't use
System.exit(0);
You should not free that memory, the system will do it for you if need it. This is the intended behaviour. -
DragonFire about 4 yearsi find that using System.exit(0); logs out the user from firebase, then after the app is started the user is required to log in again... it also seems to clear the shared preferences, permissions etc.
-
Androidcoder about 4 yearsIt used to be preached as bad practice to ever programmatically quit an app, even with an exit button. I never agreed with this. I notice Fortnite presents a dialogue requesting developer mode be disabled and then closing its app after a period of time if debugging is on while running their app. That's one particularly good example why you might want to programmatcally quit.
-
Akash Jain almost 4 yearswell a use case for "kill all activities" could be an exit button which exists (and removes) all it's activities...
-
Evgeny Gerbut almost 4 yearsYou said it will close app without showing ANR dialog. Does it mean Google store won't be informated about ANR event?
-
Muji Tech almost 4 yearsuse it and leave a comment
-
famfamfam over 3 yearsbest answer here, other didnt try above solutions, nothing work without this solution
-
bnGG over 3 years@EvgenyGerbut I have never run this code snippet in a published app, it was for science only. But I am pretty sure, that if you catch your own ANRs and close the application without an error, Google will not be informed about the ANR.
-
Nasib about 3 yearsThe best answer. I actually needed to restart my app for that I added startActivity(new Intent(this, SplashAcitivity.class)); before calling finish(); in onCreate in this ExitActivity and that's pretty awesome.
-
Robert Page almost 3 yearsWhy is
System.exit(0)
getting frowned upon? -
Brian M over 2 yearsKotlin version: finishAffinity(); exitProcess(0); Thank you Dolan, this is what I needed nothing below worked