Android: Quit application when press back button

Viewed 141388

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

try this

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

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
    }

}
Related