How to quit android application programmatically

448,120

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

  1. 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.
  2. 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?
  3. 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);
    }

}
Share:
448,120
Vignesh
Author by

Vignesh

Updated on January 04, 2021

Comments

  • Vignesh
    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?

    1. System.runFinalizersOnExit(true)
      (OR)
    2. 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
    Tanner Perrien about 13 years
    Calling 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
    Nanne about 13 years
    Finish will kill the activity. how is this different then killing the appliation?
  • Tanner Perrien
    Tanner Perrien about 13 years
    There is nothing wrong with "finishing" or "killing" the Activity (not the Application). For example, you might start a new activity to show the user some information. After a timeout or pressing 'OK' you might call finish() to return to the calling activity.
  • CommonsWare
    CommonsWare about 13 years
    Most Android applications have more than one activity.
  • Nanne
    Nanne about 13 years
    So you need to kill more then one activity, true, but the concept is the same, isn't it?
  • anonim
    anonim about 12 years
    sign 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
    Dave Appleton almost 12 years
    Nanne - 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
    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
    Sydwell about 10 years
    I 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
    Peter almost 10 years
    finish it's not a way.. app steel running
  • mz87
    mz87 almost 10 years
    yeah, works great! Have to call this from MainActivity to get it to work!
  • Romulus Urakagi Ts'ai
    Romulus Urakagi Ts'ai over 9 years
    Finishing an Activity differs too much from terminating an Application with lots of Activities and Services. This is a bad answer.
  • Managarm
    Managarm over 9 years
    By keeping a reference to your activity you are actually leaking memory! See this for an in-depth discussion.
  • Jabari
    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
    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
    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
    IAmTheSquidward over 9 years
    Perfect 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
    superuserdo over 9 years
    Perfect Solution really. Fixed a lot of problems. Thanks.
  • 030
    030 over 9 years
  • Antonio
    Antonio about 9 years
    Definitely 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
    Antonio about 9 years
    I 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
    user3290180 almost 9 years
    this is not the solution, it doesn't work if you have a stack of activities
  • 2Dee
    2Dee almost 9 years
    finish() will close an Activity, but will certainly not close the entire app with certainty.
  • Script Kitty
    Script Kitty over 8 years
    Do you know if there is another solution on API 14? Thanks
  • sivi
    sivi over 8 years
    You can finish() each activity individualy, either when you close the app or inside the activity lifcycle.
  • LiangWang
    LiangWang over 8 years
    as user3290180 pointed out, it's not a solution when you have multiple activities
  • Weiyi
    Weiyi over 8 years
    Clear all activities in the second app, and navigate back to the first app! Solve my problem ;-)
  • tryp
    tryp about 8 years
    Nice to know, thank you for the trick. It's better than the "raw" solution "System.exit(0);"
  • Laogeodritt
    Laogeodritt almost 8 years
    This quite the current Android component (e.g. activity), not the entire app.
  • Prashanth Debbadwar
    Prashanth Debbadwar almost 8 years
    Hi, can I do it in intent service(GcmListenerService)? The intent service will be called when pn comes.
  • Mr. Nobody
    Mr. Nobody almost 8 years
    worked without any problem. For api>=16 use finishAffinity() else use this method.
  • Tasneem
    Tasneem over 7 years
    This 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
    Tasneem over 7 years
    When 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
    Kumar Gaurav over 6 years
    This will only send the app in the background
  • driftwood
    driftwood over 6 years
    this is the correct answer, i was looking for. thanks
  • Tincho825
    Tincho825 over 6 years
    WARNING! this.finishAffinity() closes app removing it from memory, so you wont receive push messages and so.
  • YellowJ
    YellowJ about 6 years
    finishAndRemoveTask() did not work on Android N HTC One m9 device. It just finished the current activity. finishAffinity() did.
  • Slav
    Slav about 6 years
    This 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
    iOS-Coder almost 6 years
    The 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
    DoruChidean over 5 years
    This is the most voted answer however it is a hack. Calling finish in onCreate will look glitchy on most, if not all, devices.
  • vivek
    vivek over 5 years
    Hmm 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
    Taslim Oseni over 5 years
    Remember to declare this class in your manifest. +1 for the clever hack though.
  • Heetola
    Heetola over 5 years
    this is just freezing my app.
  • AxA
    AxA over 5 years
    Does this just bring home screen or actually kills the app?
  • ivan8m8
    ivan8m8 over 5 years
    Process.killProcess(Process.myPid()) does the same, but is shorter
  • Edgar Khimich
    Edgar Khimich almost 5 years
    In 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ć
    Dragan Marjanović almost 5 years
    This helped us make RetryRule works in our flakey connected tests.
  • roghayeh hosseini
    roghayeh hosseini over 4 years
    if i used FCM , or background tasks in my app, I would have no problem?
  • Edgar Khimich
    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
    kz_sergey over 4 years
    This answer is not correct. Use finishAffinity(); System.exit(0);
  • A1m
    A1m over 4 years
    This was what I needed to wipe the application from memory
  • crgarridos
    crgarridos about 4 years
    please 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
    DragonFire about 4 years
    i 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
    Androidcoder about 4 years
    It 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
    Akash Jain almost 4 years
    well a use case for "kill all activities" could be an exit button which exists (and removes) all it's activities...
  • Evgeny Gerbut
    Evgeny Gerbut almost 4 years
    You said it will close app without showing ANR dialog. Does it mean Google store won't be informated about ANR event?
  • Muji Tech
    Muji Tech almost 4 years
    use it and leave a comment
  • famfamfam
    famfamfam over 3 years
    best answer here, other didnt try above solutions, nothing work without this solution
  • bnGG
    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
    Nasib about 3 years
    The 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
    Robert Page almost 3 years
    Why is System.exit(0) getting frowned upon?
  • Brian M
    Brian M over 2 years
    Kotlin version: finishAffinity(); exitProcess(0); Thank you Dolan, this is what I needed nothing below worked