39

In my application i want exit from app when press back button, this my code:

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                .setMessage("Are you sure you want to exit?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setNegativeButton("No", null).show();
    }

it's work correctly but when i exit from app it does not exit completely and show empty page with my app logo and when i again press back button exit from app, How can i fix it???

EDIT :

I use this code instead of above but my app exit completely but i want it running at background and does not exit completely , how can i do it?

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                .setMessage("Are you sure?")
                .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    }
                }).setNegativeButton("no", null).show();
    } 
Elham Gdz
  • 1,015
  • 3
  • 15
  • 31

13 Answers13

105

When you press back and then you finish your current activity(say A), you see a blank activity with your app logo(say B), this simply means that activity B which is shown after finishing A is still in backstack, and also activity A was started from activity B, so in activity, You should start activity A with flags as

Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                  
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);

Now your activity A is top on stack with no other activities of your application on the backstack.

Now in the activity A where you want to implement onBackPressed to close the app, you may do something like this,

private Boolean exit = false;
@Override
    public void onBackPressed() {
        if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

        }

    }

The Handler here handles accidental back presses, it simply shows a Toast, and if there is another back press within 3 seconds, it closes the application.

Rachit Mishra
  • 6,101
  • 4
  • 30
  • 51
  • i just don't know what is "NEXT_ACTIVITY" in my app, i add my code in activity that i want exit button works at this page but in your code i don't know which my page will be NEXT_ACTIVITY. – Elham Gdz Dec 15 '13 at 07:10
  • Elegant. Just not sure what Home.this is. Just removed it and left finish(); – samleighton87 Dec 21 '14 at 14:49
  • @samleighton87 yup that's not required, just finish will work. (Home was my activity name) – Rachit Mishra Dec 24 '14 at 09:57
  • For documentation on `Intent` options/flags/etc, see [here](https://developer.android.com/reference/android/content/Intent.html) – code_dredd Jul 11 '17 at 23:28
46

Try this:

Intent intent = new Intent(Intent.ACTION_MAIN);
          intent.addCategory(Intent.CATEGORY_HOME);
          intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
          startActivity(intent);
          finish();
          System.exit(0);
Md. Ilyas Hasan Mamun
  • 1,848
  • 2
  • 24
  • 15
  • Thank you! It hands on restart without `System.exit(0);` – Ivan V Jul 13 '15 at 13:20
  • Bad practice , to kill application from home button , and use System.exit(0); we must keep the system kill application after click on back button in the last activity – Sofien Rahmouni Dec 29 '15 at 16:02
23

I had the Same problem, I have one LoginActivity and one MainActivity. If I click back button in MainActivity, Application has to close. SO I did with OnBackPressed method. this moveTaskToBack() work as same as Home Button. It leaves the Back stack as it is.

public void onBackPressed() {
  //  super.onBackPressed();
    moveTaskToBack(true);

}
Tara
  • 2,598
  • 1
  • 21
  • 30
5

It means your previous activity in stack when you start this activity. Add finish(); after the line in which you calling this activity.

In your all previous activity. when you start new activity like-

startActivity(I);

Add finish(); after this.

Kanwaljit Singh
  • 4,339
  • 2
  • 18
  • 21
3

In my understanding Google wants Android to handle memory management and shutting down the apps. If you must exit the app from code, it might be beneficial to ask Android to run garbage collector.

@Override
public void onBackPressed(){
    System.gc();
    System.exit(0);
}

You can also add finish() to the code, but it is probably redundant, if you also do System.exit(0)

Matti
  • 147
  • 5
2

nobody seems to have recommended noHistory="true" in manifest.xml to prevent certain activity to appear after you press back button which by default calling method finish()

1

Finish doesn't close the app, it just closes the activity. If this is the launcher activity, then it will close your app; if not, it will go back to the previous activity.

What you can do is use onActivityResult to trigger as many finish() as needed to close all the open activities.

gian1200
  • 3,670
  • 2
  • 30
  • 59
  • please check Edit, i want when i close my app it running at the background , how can i do it? – Elham Gdz Dec 15 '13 at 07:25
  • @ElhamGdz can you please rephrase your sentence? I can't understand you. If you check the Activity Lifecycle, there is no state "running on background" it is either running or not running. http://developer.android.com/training/basics/activity-lifecycle/index.html. If you want to run some code on the background, then you may need an Async or (as a last option) a Service http://developer.android.com/reference/android/app/Service.html – gian1200 Dec 21 '13 at 00:48
1

This one work for me.I found it myself by combining other answers

private Boolean exit = false;
@override
public void onBackPressed(){ 
    if (exit) {
        finish(); // finish activity
    } 
    else {
        Toast.makeText(this, "Press Back again to Exit.",
            Toast.LENGTH_SHORT).show();
         exit = true;
         new Handler().postDelayed(new Runnable() {

         @Override
         public void run() {
             // TODO Auto-generated method stub
             Intent a = new Intent(Intent.ACTION_MAIN);
             a.addCategory(Intent.CATEGORY_HOME);
             a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(a);
        }
    }, 1000);
}
Ajil O.
  • 6,562
  • 5
  • 40
  • 72
Bivin
  • 375
  • 3
  • 24
1

In order to exit from the app on pressing back button you have to first clear all the top activities and then start the ACTION_MAIN of android phone

So, you have to write all these code only which is mentioned below :

Note : In your case MainActivity get replaced by YourActivity

@Override
public void onBackPressed() {

        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.super.onBackPressed();
                        quit();
                    }
                }).create().show();
    }


public void quit() {
        Intent start = new Intent(Intent.ACTION_MAIN);
        start.addCategory(Intent.CATEGORY_HOME);
        start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        start.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(start);
    }
Aman Kumar Gupta
  • 2,640
  • 20
  • 18
1

try this

Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
BIS Tech
  • 17,000
  • 12
  • 99
  • 148
0

Instead of finish() call super.onBackPressed()

Shashika
  • 1,151
  • 1
  • 9
  • 21
  • @Shasika: what you said is not true, it is not true that call one method inside it, i can't call onBackPressed() inside it!!! – Elham Gdz Dec 15 '13 at 06:59
0

I found good solution:

@Override
public void onBackPressed() {

    int idItem = navView.getSelectedItemId();
    if (R.id.navigation_home == idItem){
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("do you want to go back sir?")
                .setCancelable(true)
                .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {

                        dialog.dismiss();

                    }
                });
        builder.create().show();
    }
    else{
        super.onBackPressed();  // this line make back action
    }

}
halfer
  • 19,824
  • 17
  • 99
  • 186
m0haMed
  • 420
  • 5
  • 7
-6

Use this code very simple solution

 @Override
    public void onBackPressed() {
      super.onBackPressed(); // this line close the  app on backpress
 }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
bambi
  • 33
  • 8
  • 3
    what is the purpose of overriding some method and calling only super implementation? – pskink Jan 16 '16 at 10:54
  • Wrong answer. `super.onBackPressed()` won't quit the app unless this is the root activity. Besides, why override if you do nothing but calling `super`? – Pang Jan 17 '16 at 05:44