Question

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();
    } 
Was it helpful?

Solution

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.

OTHER TIPS

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

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

}

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.

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)

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

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.

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

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

try this

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

Instead of finish() call super.onBackPressed()

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
    }

}

Use this code very simple solution

 @Override
    public void onBackPressed() {
      super.onBackPressed(); // this line close the  app on backpress
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top