How to quit android application programmatically

Android

Android Problem Overview


I found some codes for quitting an Android application programmatically. By calling any one of the following codes in onDestroy(), will it quit 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?

Android Solutions


Solution 1 - Android

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 - Android

getActivity().finish();
System.exit(0);

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

The best solution for me.

Solution 3 - Android

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 - Android

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: https://stackoverflow.com/questions/2033914/quitting-an-application-is-that-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 - Android

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

}

Solution 6 - Android

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.

Solution 7 - Android

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

Solution 8 - Android

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

Solution 9 - Android

You can use finishAndRemoveTask () from API 21

> public void finishAndRemoveTask () > > > Finishes all activities in this task and removes it from the recent tasks list.

Solution 10 - Android

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.

Solution 11 - Android

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

Solution 12 - Android

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

Solution 13 - Android

Similar to @MobileMateo, but in Kotlin

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    this.finishAffinity()
} else{
    this.finish()
    System.exit(0)
}

Solution 14 - Android

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

Solution 15 - Android

I think what you are looking for is this

activity.moveTaskToBack(Boolean nonRoot);

Solution 16 - Android

If you want to close your app:

For API >= 21, use:

finishAndRemoveTask();

For API < 21 use:

finishAffinity();

Solution 17 - Android

public void quit() {
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
        System.exit(0);
    }

Solution 18 - Android

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.

Solution 19 - Android

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

public void onBackPressed() 
{

    finishAffinity();
    System.exit(0);
}

Solution 20 - Android

https://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238#2034238. 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.

Solution 21 - Android

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!

Solution 22 - Android

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

Solution 23 - Android

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.

Solution 24 - Android

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

Solution 25 - Android

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.

Solution 26 - Android

This will kill anything ;)

int p = android.os.Process.myPid();
android.os.Process.killProcess(p);

Solution 27 - Android

Try this

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

Solution 28 - Android

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

Solution 29 - Android

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

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

Solution 30 - Android

@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>

Solution 31 - Android

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

Solution 32 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVigneshView Question on Stackoverflow
Solution 1 - AndroidsiviView Answer on Stackoverflow
Solution 2 - AndroidAshtonView Answer on Stackoverflow
Solution 3 - AndroidCristian BabarusiView Answer on Stackoverflow
Solution 4 - AndroidNanneView Answer on Stackoverflow
Solution 5 - AndroidvivekView Answer on Stackoverflow
Solution 6 - AndroidsunghunView Answer on Stackoverflow
Solution 7 - AndroidsanView Answer on Stackoverflow
Solution 8 - Androidtwenk11kView Answer on Stackoverflow
Solution 9 - AndroidVinsView Answer on Stackoverflow
Solution 10 - Androiduser3424426View Answer on Stackoverflow
Solution 11 - AndroidFarruh HabibullaevView Answer on Stackoverflow
Solution 12 - AndroidHassnain JamilView Answer on Stackoverflow
Solution 13 - AndroidJerry ChongView Answer on Stackoverflow
Solution 14 - AndroidMobileMateoView Answer on Stackoverflow
Solution 15 - AndroidCiprianView Answer on Stackoverflow
Solution 16 - AndroidSagittariusView Answer on Stackoverflow
Solution 17 - AndroidmeduvigoView Answer on Stackoverflow
Solution 18 - AndroidMicerView Answer on Stackoverflow
Solution 19 - AndroidMuji TechView Answer on Stackoverflow
Solution 20 - AndroidRaghunandanView Answer on Stackoverflow
Solution 21 - AndroidJabariView Answer on Stackoverflow
Solution 22 - AndroidamrezzdView Answer on Stackoverflow
Solution 23 - AndroidAalok SharmaView Answer on Stackoverflow
Solution 24 - AndroidPir Fahim ShahView Answer on Stackoverflow
Solution 25 - AndroidEgorView Answer on Stackoverflow
Solution 26 - AndroidD.SnapView Answer on Stackoverflow
Solution 27 - AndroidAhmer AfzalView Answer on Stackoverflow
Solution 28 - Androiduser1079425View Answer on Stackoverflow
Solution 29 - AndroidDaniel FView Answer on Stackoverflow
Solution 30 - AndroidSaeed VrzView Answer on Stackoverflow
Solution 31 - Androidkhushal rasaliView Answer on Stackoverflow
Solution 32 - AndroidRaj KumarView Answer on Stackoverflow