[android] How to exit when back button is pressed?

When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?

This question is related to android exit back-button

The answer is


To exit from an Android app, just simply use. in your Main Activity, or you can use Android manifest file to set

android:noHistory="true"

you can simply use this

 startActivity(new Intent(this, Splash.class));
 moveTaskToBack(true);

The startActivity(new Intent(this, Splash.class)); is the first class that will be lauched when the application starts

moveTaskToBack(true); will minimize your application


Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.

If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).

If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.


A better user experience:

/**
 * Back button listener.
 * Will close the application if the back button pressed twice.
 */
@Override
public void onBackPressed()
{
    if(backButtonCount >= 1)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
        backButtonCount++;
    }
}

finish your current_activity using method finish() onBack method of your current_activity

and then add below lines in onDestroy of the current_activity for Removing Force close

@Override
public void onDestroy()
{
    android.os.Process.killProcess(android.os.Process.myPid());
    super.onDestroy();
}

First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.

Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.

Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html

But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:

@Override
 public void onBackPressed() {

// make sure you have this outcommented
// super.onBackPressed();
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);
}

In my Home Activity I override the "onBackPressed" to:

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

so if the user is in the home activity and press back, he goes to the home screen.

I took the code from Going to home screen Programmatically


The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed

<activity android:name=".activities.DemoActivity"
            android:screenOrientation="portrait"
            **android:noHistory="true"**
            />

Use onBackPressedmethod

@Override
public void onBackPressed() {
    finish();
    super.onBackPressed();
}

This will solve your issue.


I modified @Vlad_Spays answer so that the back button acts normally unless it's the last item in the stack, then it prompts the user before exiting the app.

@Override
public void onBackPressed(){
    if (isTaskRoot()){
        if (backButtonCount >= 1){
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }else{
            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
            backButtonCount++;
        }
    }else{
        super.onBackPressed();
    }
}

Add this code in the activity from where you want to exit from the app on pressing back button:

@Override
public void onBackPressed() {
    super.onBackPressed();
    exitFromApp();
}

private void exitFromApp() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

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 exit

Ruby - ignore "exit" in code Difference between return 1, return 0, return -1 and exit? Android: Quit application when press back button How to exit a function in bash break/exit script How to use sys.exit() in Python exit application when click button - iOS How to properly exit a C# application? What is the command to exit a Console application in C#? Get exit code for command in bash/ksh

Examples related to back-button

Android: Quit application when press back button JavaScript or jQuery browser back button click detector Clicking the back button twice to exit an activity How to exit from the application and show the home screen? Android - How To Override the "Back" button so it doesn't Finish() my Activity? Preventing iframe caching in browser How to exit when back button is pressed?