406

I found some code for quitting an Android application programmatically. By using any of the following code in onDestroy(), will it quit the application entirely?

  1. System.runFinalizersOnExit(true)
    (OR)
  2. android.os.Process.killProcess(android.os.Process.myPid());

I don't want to run my application in background after clicking quit button. Please inform me if I can use any one of these codes to quit my app? If so, which code can I use? Is it good way to quit the app in Android?

starball
  • 20,030
  • 7
  • 43
  • 238
Vignesh
  • 8,319
  • 6
  • 22
  • 11
  • There are so many posts already here. http://stackoverflow.com/search?q=how+to+exit+an+android+app – Mudassir Jun 13 '11 at 12:17
  • 3
    possible duplicate of [Quitting an application - is that frowned upon?](http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon) – CommonsWare Jun 13 '11 at 14:02
  • use 'System.exit(0);' when you really want to exit the app. I have done that on an unrecoverable error after showing the user a message. If you need to, you can even automatically relaunch the app using AlarmManager. See: http://blog.janjonas.net/2010-12-20/android-development-restart-application-programmatically – Someone Somewhere Aug 01 '13 at 17:52
  • The second option makes it look like a crash – Eli Jun 30 '20 at 17:04
  • I tried everything i could find. Nothing kills my background service like Force Stop does – M. Usman Khan Jun 01 '23 at 06:01

33 Answers33

533

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.

Community
  • 1
  • 1
sivi
  • 10,654
  • 2
  • 52
  • 51
  • 45
    **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 May 29 '15 at 22:48
  • 4
    Do you know if there is another solution on API 14? Thanks – Script Kitty Nov 29 '15 at 23:15
  • 2
    You can finish() each activity individualy, either when you close the app or inside the activity lifcycle. – sivi Nov 30 '15 at 06:09
  • Clear all activities in the second app, and navigate back to the first app! Solve my problem ;-) – Weiyi Mar 07 '16 at 08:00
  • Nice to know, thank you for the trick. It's better than the "raw" solution "System.exit(0);" – tryp Apr 13 '16 at 08:50
  • Hi, can I do it in intent service(GcmListenerService)? The intent service will be called when pn comes. – Prashanth Debbadwar Sep 07 '16 at 10:28
  • When I call getActivity().finishAffinity() , it does not call my Application class on clicking on the app icon while System.exit(0); does work. – Tasneem Dec 12 '16 at 10:06
  • 6
    WARNING! this.finishAffinity() closes app removing it from memory, so you wont receive push messages and so. – Tincho825 Feb 19 '18 at 17:02
  • 2
    `finishAndRemoveTask()` did not work on Android N HTC One m9 device. It just finished the current activity. `finishAffinity()` did. – YellowJ May 04 '18 at 03:23
  • 20
    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. – Slav Jun 27 '18 at 13:53
  • 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); } – iOS-Coder Aug 22 '18 at 20:46
  • this is just freezing my app. – Heetola Dec 17 '18 at 13:40
  • 8
    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 – Edhar Khimich Jul 22 '19 at 20:25
  • This helped us make RetryRule works in our flakey connected tests. – Dragan Marjanović Sep 20 '19 at 11:03
  • @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 – Edhar Khimich Jan 20 '20 at 19:34
  • 1
    This answer is not correct. Use finishAffinity(); System.exit(0); – kz_sergey Feb 19 '20 at 08:26
  • 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. – Androidcoder Jun 17 '20 at 16:40
  • Note that `finishAndRemoveTask()` and `finishAffinity()` are not the same! If you have various other `Activity`s on your backstack that you also want finished, you must call `finishAffinity()` not `finishAndRemoveTask()` as the latter will not finish all other existing Activitys on the backstack where `finishAffinity()` does. This is what my testing showed me, at least. – Smalls Nov 23 '22 at 05:16
177
getActivity().finish();
System.exit(0);

this is the best way to exit your app.!!!

The best solution for me.

Ashton
  • 2,425
  • 2
  • 22
  • 26
  • yeah, works great! Have to call this from MainActivity to get it to work! – mz87 Oct 05 '14 at 21:59
  • 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. – IAmTheSquidward Jan 08 '15 at 05:25
  • Perfect Solution really. Fixed a lot of problems. Thanks. – superuserdo Jan 13 '15 at 02:17
  • 31
    **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) – Antonio May 29 '15 at 22:53
  • 15
    this is not the solution, it doesn't work if you have a stack of activities – user3290180 Aug 12 '15 at 17:28
  • as user3290180 pointed out, it's not a solution when you have multiple activities – LiangWang Dec 06 '15 at 12:30
  • 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 Dec 12 '16 at 10:04
  • 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. – DragonFire May 11 '20 at 00:12
  • Why is `System.exit(0)` getting frowned upon? – Robert Page Jul 25 '21 at 21:56
73

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();
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
Cristian Babarusi
  • 1,455
  • 14
  • 19
30

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.

Community
  • 1
  • 1
Nanne
  • 64,065
  • 16
  • 119
  • 163
  • 36
    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. – Tanner Perrien Jun 13 '11 at 12:44
  • Finish will kill the activity. how is this different then killing the appliation? – Nanne Jun 13 '11 at 13:26
  • 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. – Tanner Perrien Jun 13 '11 at 13:55
  • 46
    Most Android applications have more than one activity. – CommonsWare Jun 13 '11 at 14:03
  • So you need to kill more then one activity, true, but the concept is the same, isn't it? – Nanne Jun 13 '11 at 15:36
  • 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. – Dave Appleton Sep 16 '12 at 04:25
  • 4
    @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! – Jabari May 30 '13 at 05:13
  • finish it's not a way.. app steel running – Peter Sep 25 '14 at 08:02
  • Finishing an Activity differs too much from terminating an Application with lots of Activities and Services. This is a bad answer. – Romulus Urakagi Ts'ai Oct 07 '14 at 04:23
  • well a use case for "kill all activities" could be an exit button which exists (and removes) all it's activities... – Akash Jain Aug 19 '20 at 15:36
24

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);
    }

}
vivek
  • 1,034
  • 11
  • 14
  • This is the most voted answer however it is a hack. Calling finish in onCreate will look glitchy on most, if not all, devices. – DoruChidean Oct 25 '18 at 12:17
  • 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. – vivek Oct 29 '18 at 07:38
  • 2
    Remember to declare this class in your manifest. +1 for the clever hack though. – Taslim Oseni Dec 03 '18 at 00:01
  • 1
    best answer here, other didnt try above solutions, nothing work without this solution – famfamfam Dec 30 '20 at 10:35
  • 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. – Nasib May 08 '21 at 17:43
22

I think that application should be kill in some case. For example, there is an app can be used only after login. The login activity has two buttons, 'login' and 'cancel'. When you click 'cancel' button, it definitely means 'Terminate the app'. Nobody wants the app alive in the background. So I agree that some cases need to shut down the app.

sunghun
  • 1,424
  • 4
  • 25
  • 49
  • 4
    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? – Sydwell Jun 04 '14 at 10:43
21

There is no application quitting in android, SampleActivity.this.finish(); will finish the current activity.

When you switch from one activity to another keep finish the previous one

Intent homeintent = new Intent(SampleActivity.this,SecondActivity.class);
startActivity(homeintent);
SampleActivity.this.finish();
Thomas Dignan
  • 7,052
  • 3
  • 40
  • 48
san
  • 490
  • 3
  • 8
20

First of all, this approach requires min Api 16.

I will divide this solution to 3 parts to solve this problem more widely.

1. If you want to quit application in an Activity use this code snippet:

if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
    finishAffinity();
} else if(Build.VERSION.SDK_INT>=21){
    finishAndRemoveTask();
}

2. If you want to quit the application in a non Activity class which has access to Activity then use this code snippet:

if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
    getActivity().finishAffinity();
} else if(Build.VERSION.SDK_INT>=21){
    getActivity().finishAndRemoveTask();
}

3. If you want to quit the application in a non Activity class and cannot access to Activity such as Service I recommend you to use BroadcastReceiver. You can add this approach to all of your Activities in your project.

Create LocalBroadcastManager and BroadcastReceiver instance variables. You can replace getPackageName()+".closeapp" if you want to.

LocalBroadcastManager mLocalBroadcastManager;
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(getPackageName()+".closeapp")){
            if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
                finishAffinity();
            } else if(Build.VERSION.SDK_INT>=21){
                finishAndRemoveTask();
            }
        }
    }
};

Add these to onCreate() method of Activity.

mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(getPackageName()+".closeapp");
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);

Also, don't forget to call unregister receiver at onDestroy() method of Activity

mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);

For quit application, you must send broadcast using LocalBroadcastManager which I use in my PlayService class which extends Service.

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(PlayService.this);
localBroadcastManager.sendBroadcast(new Intent(getPackageName() + ".closeapp"));
Rutvik Bhatt
  • 3,185
  • 1
  • 16
  • 28
twenk11k
  • 557
  • 5
  • 17
13

You can use finishAndRemoveTask () from API 21

public void finishAndRemoveTask ()

Finishes all activities in this task and removes it from the recent tasks list.

Vins
  • 4,089
  • 2
  • 35
  • 50
12

If you want to close your app:

For API >= 21, use:

finishAndRemoveTask();

For API < 21 use:

finishAffinity();
Sagittarius
  • 355
  • 3
  • 6
11

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);
ᴛʜᴇᴘᴀᴛᴇʟ
  • 4,466
  • 5
  • 39
  • 73
Farruh Habibullaev
  • 2,342
  • 1
  • 26
  • 33
10

It depends on how fast you want to close your app.

A safe way to close your app is finishAffinity();

It closes you app after all processes finished processing. This may need some time. If you close your app this way, and restart it after a short time, it is possible that your new application runs in the same process. With all the not finished processes and singleton objects of the old application.

If you want to be sure, that your app is closed completly use System.exit(0);

This will close your app immediatly. But it is possible, that you damage files that your app has open or an edit on shared preferences does not finish. So use this carefully.

If you use watchdog in combination with a long running task, you can see the influences of the different methods.

new ANRWatchDog(2000).setANRListener(new ANRWatchDog.ANRListener() {
    public void onAppNotResponding(ANRError error) {
        MainActivity.this.finishAffinity();
        System.exit(0);
    }
}).start();
for(int i = 0; i < 10; ++i){
    --i;
}

This kills your app after 2 seconds without displaying an ANR dialog or something like that. If you remove System.exit(0), run this code and restart the app after it is closed, you will experience some strange behaviour, because the endless loop is still running.

bnGG
  • 191
  • 3
  • 9
  • You said it will close app without showing ANR dialog. Does it mean Google store won't be informated about ANR event? – Evgeny Gerbut Sep 08 '20 at 12:56
  • @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. – bnGG Jan 12 '21 at 20:02
9

Easy and simple way to quit from the application

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
Hassnain Jamil
  • 1,651
  • 17
  • 21
9

Similar to @MobileMateo, but in Kotlin

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    this.finishAffinity()
} else{
    this.finish()
    System.exit(0)
}
Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
8

We want code that is robust and simple. This solution works on old devices and newer devices.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        getActivity().finishAffinity();
    } else{
        getActivity().finish();
        System.exit( 0 );
    }
MobileMateo
  • 424
  • 5
  • 4
8

Friends just add this function to exit your application programmatically #java

public void onBackPressed() 
{

    finishAffinity();
    System.exit(0);
}
B. Go
  • 1,436
  • 4
  • 15
  • 22
Muji Tech
  • 21
  • 1
  • 2
7

I think what you are looking for is this

activity.moveTaskToBack(Boolean nonRoot);
Ciprian
  • 2,879
  • 3
  • 28
  • 28
6

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.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
6
public void quit() {
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
        System.exit(0);
    }
meduvigo
  • 1,523
  • 12
  • 7
  • 4
    [System.exit() does not kill the Android Application if there is more than one activity](http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2043734#2043734) – 030 Mar 17 '15 at 13:19
6

If you're using Kotlin, the proper way to exit the app and alternative to System.exit() is a built-in method

exitProcess(0)

See the documentation.

Number 0 as a parameter means the exit is intended and no error occurred.

Micer
  • 8,731
  • 3
  • 79
  • 73
5

I'm not sure if this is frowned upon or not, but this is how I do it...

Step 1 - I usually have a class that contains methods and variables that I want to access globally. In this example I'll call it the "App" class. Create a static Activity variable inside the class for each activity that your app has. Then create a static method called "close" that will run the finish() method on each of those Activity variables if they are NOT null. If you have a main/parent activity, close it last:

public class App
{
    ////////////////////////////////////////////////////////////////
    // INSTANTIATED ACTIVITY VARIABLES
    ////////////////////////////////////////////////////////////////

        public static Activity activity1;
        public static Activity activity2;
        public static Activity activity3;

    ////////////////////////////////////////////////////////////////
    // CLOSE APP METHOD
    ////////////////////////////////////////////////////////////////

        public static void close()
        {
            if (App.activity3 != null) {App.activity3.finish();}
            if (App.activity2 != null) {App.activity2.finish();}
            if (App.activity1 != null) {App.activity1.finish();}
        }
}

Step 2 - in each of your activities, override the onStart() and onDestroy() methods. In onStart(), set the static variable in your App class equal to "this". In onDestroy(), set it equal to null. For example, in the "Activity1" class:

@Override
public void onStart()
{
    // RUN SUPER | REGISTER ACTIVITY AS INSTANTIATED IN APP CLASS

        super.onStart();
        App.activity1 = this;
}

@Override
public void onDestroy()
{
    // RUN SUPER | REGISTER ACTIVITY AS NULL IN APP CLASS

        super.onDestroy();
        App.activity1 = null;
}

Step 3 - When you want to close your app, simply call App.close() from anywhere. All instantiated activities will close! Since you are only closing activities and not killing the app itself (as in your examples), Android is free to take over from there and do any necessary cleanup.

Again, I don't know if this would be frowned upon for any reason. If so, I'd love to read comments on why it is and how it can be improved!

Jabari
  • 5,359
  • 3
  • 26
  • 32
  • 4
    By keeping a reference to your activity you are actually leaking memory! See [this](http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html) for an in-depth discussion. – Managarm Oct 25 '14 at 22:47
  • @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. – Jabari Oct 26 '14 at 07:08
  • @Jabari Ah, I missed the onDestroy part. In that case it should not be an issue, though it's not best practice. – Managarm Oct 26 '14 at 11:53
  • @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! – Jabari Oct 26 '14 at 16:37
  • 1
    worked without any problem. For `api>=16` use `finishAffinity()` else use this method. – Mr. Nobody Sep 28 '16 at 06:14
5

To exit you application you can use the following:

getActivity().finish();
Process.killProcess(Process.myPid());
System.exit(1);

Also to stop the services too call the following method:

private void stopServices() {        
    final ActivityManager activityManager = SystemServices.getActivityManager(context);
    final List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
    final int pid = Process.myPid();
    for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
        if (serviceInfo.pid == pid && !SenderService.class.getName().equals(serviceInfo.service.getClassName())) {
            try {
                final Intent intent = new Intent();
                intent.setComponent(serviceInfo.service);
                context.stopService(intent);
            } catch (SecurityException e) { 
                 // handle exception
            }
        }
    }
}
amrezzd
  • 1,787
  • 15
  • 38
3

This may be very late and also as per the guidelines you're not supposed to handle the life cycle process by yourself(as the os does that for you). A suggestion would be that you register a broadcast receiver in all your activities with "finish()" in their onReceive() & whenever you wish to quit you can simple pass an intent indicating that all activities must shut down..... Although make sure that you do "unregister" the receiver in your onDestroy() methods.

Aalok Sharma
  • 1,025
  • 2
  • 12
  • 26
2

The correct and exact solution to quit the app on button click is using the below code:

//On Button Back pressed event

public void onBackPressed()
{ 
   moveTaskToBack(true);
   finish();
}
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
2

@Sivi 's answer closes the app. But on return, if you have some child activities, another unfinished activity might be opened. I added noHistory:true to my activities so the app on return starts from MainActivity.

<activity 
      android:name=".MainActivity"
      android:noHistory="true">
</activity>
Saeed Vrz
  • 147
  • 1
  • 3
  • 10
1

This will kill anything ;)

int p = android.os.Process.myPid();
android.os.Process.killProcess(p);
D.Snap
  • 1,704
  • 1
  • 22
  • 15
1

Try this

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Ahmer Afzal
  • 501
  • 2
  • 11
  • 24
1

The easiest way I found to quit an application from an activity, without breaking Android's logic and without adding more code in existing activities and passing extras is the following:

public static void quitApplication (Activity currentActivity) {
    Intent intent = new Intent (currentActivity, QuitApplicationActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    currentActivity.startActivity (intent);
    currentActivity.finish ();
}

the QuitApplicationActivity being:

public class QuitApplicationActivity extends AppCompatActivity {

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);

        finish ();
    }
}
1

Just to add one to the list of brutal methods of terminating an App:

Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);

Daniel F
  • 13,684
  • 11
  • 87
  • 116
1

It's not a good decision, cause it's against the Android's application processing principles. Android doesn't kill any process unless it's absolutely inevitable. This helps apps start faster, cause they're always kept in memory. So you need a very special reason to kill your application's process.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • 4
    sign out of an application requires to really kill the app. so there should be a way to ensure app killed after signing out – anonim May 11 '12 at 00:56
0

What I observed is finishAffinity() finishes the app but the app is still visible in the recents screen and when you click on app in recent screen, either the previously opened activity is opened or launcher activity is opened. However I wanted the app to be removed/destroyed from recent screen as well once I do some operation.

For Example: Paytm opens MyUPIPaymentApp and once payment is made in MyUPIPaymentApp, I want control to go back to Paytm and also MyUPIPaymentApp should not be in recent app screen. I was able to achieve this behaviour using finishAndRemoveTask()

setResult(RESULT_OK, getResponseString())
finishAndRemoveTask()
Ramakrishna Joshi
  • 1,442
  • 17
  • 22
-3

Just use finish() on back key press onKeypressed()

khushal rasali
  • 221
  • 2
  • 4
  • 4
    finish() will close an Activity, but will certainly not close the entire app with certainty. – 2Dee Sep 24 '15 at 13:05
-4

Write this code in your on backpressed override method

@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}
Raj Kumar
  • 688
  • 8
  • 18