[java] How to exit an Android app programmatically?

I am sure this question has been asked number of times because I read a few. My client wants me to put a button into his app where users can click and exit. I have read this and found calling finish() will do it. But, finish is only closing the current running activity right? I have lot of activities so in this case I have to pass each and every activity's instance and finish them or make every activity into Singleton pattern.

I also got to know Activity.moveTaskToBack(true) can get you into the home screen. OK, this is not closing but backgrounding the process. So is this is effective?

Which method should I use to close the app completely? Any of above described or any other method/other usage of above methods?

This question is related to java android eclipse android-activity

The answer is


Achieving in Xamarin.Android:

    public override void OnBackPressed()
    {
        MoveTaskToBack(true);
        Process.KillProcess(Process.MyPid());
        Environment.Exit(1);
    }

android.os.Process.killProcess(android.os.Process.myPid());

If someone still wonders, for Xamarin.Android (in my case also Monogame running on it) the command FinishAndRemoveTask() on Activity does the job very well!


Accually there are two possible situations:

  1. You may want to exit from the activity
  2. Or you want to exit from the application

You can exit from the activity using following code:

var intent = new Intent(Intent.ActionMain);
intent.AddCategory(Intent.CategoryHome);
intent.SetFlags(ActivityFlags.NewTask);
startActivity(intent);
finish();

But this will not kill the underlying activities in the same application. This will just minimize the application.

If you want to exit from application use the following code to end its process:

android.os.Process.killProcess(android.os.Process.myPid()); 

for mono development just use

process.KillProcess(Process.MyPid());

Just call this:

finishAffinity();

Instead of System.exit(1) Just use System.exit(0)


If you want to exit from your application, use this code inside your button pressed event:

public void onBackPressed() {
  moveTaskToBack(true);
  android.os.Process.killProcess(android.os.Process.myPid());
  System.exit(1);
}

The finishAffinity method, released in API 16, closes all ongoing activities and closes the app:

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 in to 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:

finishAndRemoveTask();

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

Alternatives:

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


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


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


Intent i = new Intent(context, LoginActivity.class);
i.putExtra(EXTRA_EXIT, true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(i);

Source: How to quit android application programmatically


Hope it helps! Good Luck!


 @Override
    public void onBackPressed() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("Exit Application?");
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                moveTaskToBack(true);
                                android.os.Process.killProcess(android.os.Process.myPid());
                                System.exit(1);
                            }
                        })

                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

put this one into your onClic:

moveTaskToBack(true);
    finish()

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

worked for me


How about this.finishAffinity()

From the docs,

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 in to 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.


Just call these two functions

 finish();
 moveTaskToBack(true);

ghost activity called with singletop and finish() on onCreate should do the trick


Link this method to your quit/exit button

public void quitGame(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAndRemoveTask();
        } else {
            finish();
        }
    }

If you use both finish and exit your app will close complitely

finish();

System.exit(0);


It works using only moveTaskToBack(true);


this will clear Task(stack of activities) and begin new Task

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(1);

just use the code in your backpress

                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                    startMain.addCategory(Intent.CATEGORY_HOME);
                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(startMain);

It's way too easy. Use System.exit(0);


This can work I tried it too.

this.finishAffinity();


 @Override
    public void onBackPressed() {
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory( Intent.CATEGORY_HOME );
        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(homeIntent);
    }

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
System.exit(1);

Use this Code it's much useful, and you can exit all of the activities.


You can call System.exit(); to get out of all the acivities.

    submit=(Button)findViewById(R.id.submit);

            submit.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
                    System.exit(1);

                }
            });

Try this on a call. I sometimes use it in onClick of a button.

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

It instead of closing your app , opens the dashboard so kind of looks like your app is closed.

read this question for more clearity android - exit application code


in the fragment

getActivity().finishAndRemoveTask();

in the Activity

finishAndRemoveTask();


Actually every one is looking for closing the application on an onclick event, wherever may be activity....

So guys friends try this code. Put this code on the onclick event

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
    homeIntent.addCategory( Intent.CATEGORY_HOME );
    homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
    startActivity(homeIntent); 

Just run the below two lines when you want to exit from the application

android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);

Use this.finishAffinity(); on that button instead of finish(); If it does not work then you can also try by adding android:noHistory="true" in your manifest and then finish your activity by uisng finish(); or finishAffinity();

Hope it helps....:)


If you are using EventBus (or really any other pub/sub library) in your application to communicate between activities you can send them an explicit event:

final public class KillItWithFireEvent
{
    public KillItWithFireEvent() {}

    public static void send()
    {
        EventBus.getDefault().post(new KillItWithFireEvent());
    }
}

The only downside of this is you need all activities to listen to this event to call their own finish(). For this you can easily create shim activity classes through inheritance which just listen to this event and let subclasses implement everything else, then make sure all your activities inherit from this extra layer. The kill listeners could even add some extra functionality through overrides, like avoiding death on certain particular situations.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items