48

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?

12 Answers 12

100

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

0
50

Immediately after you start a new activity, using startActivity, make sure you call finish() so that the current activity is not stacked behind the new one.

EDIT With regards to your comment:

What you're suggesting is not particularly how the android app flow usually works, and how the users expect it to work. What you can do if you really want to, is to make sure that every startActivity leading up to that activity, is a startActivityForResult and has an onActivityResult listener that checks for an exit code, and bubbles that back. You can read more about that here. Basically, use setResult before finishing an activity, to set an exit code of your choice, and if your parent activity receives that exit code, you set it in that activity, and finish that one, etc...

1
  • 1
    i think you didn't understand the case, my question is when user click on specific one activity which i choose pressing back button over it should make call exit from app
    – d-man
    Mar 1, 2010 at 9:05
33

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++;
    }
}
2
  • 1
    Great job. A few other things I would add is setting a member variable to the Toast.makeText call (e.g. Toast myToast=Toast.makeText()), then using that on backButtonCount >= 1, calling .cancel() on that toast. I lengthened the duration to Toast.LENGTH_LONG for my purposes because for the amount of text the duration seemed short. My users are old people. Also, as is probably obvious, backButtonCount is a member variable set to 0 and should also be set to 0 inside your first if statement.
    – Joel Teply
    Sep 1, 2013 at 16:42
  • I also add "android.os.Process.killProcess(android.os.Process.myPid());" so my application gets killed and restart if the user click on it again
    – ChRoNoN
    Dec 22, 2016 at 13:54
4

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"**
            />
2

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.

2

Use onBackPressedmethod

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

This will solve your issue.

1
  • That is wrong. super.onBackPressed(); should be called first
    – Flot2011
    Jan 6, 2021 at 22:36
1

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

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"
0

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

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

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

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.