superseed77
superseed77

Reputation: 213

Back button and last activity

My app chains some activities.

if you press the back button, you go back through old activities then you suddenly quit the application !

so I need to show a message like "do you really want to exit" if it's the last activity on stack

I know how to override the back button but i can't figure how to know how many activity are in history

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // Is it the last activity on stack ? 
        // so show confirm dialog
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Please help.

Upvotes: 10

Views: 2304

Answers (2)

Europa
Europa

Reputation: 147

You needn't know how many activity are in history.You can do this way.Invoke the method of onBackPressed() when back button is clicked.Then override the method of finish() in your main activity to show confirm dialog.Because onBackPressed() method invoke activity's finish() method.When backing to the main activity,the overriding finish() method is invoked,there will show the dialog you have overrided.

Upvotes: 0

Jorgesys
Jorgesys

Reputation: 126465

you can achieve that using the finish() function

public void finish() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("do you really want to exit?");
        builder.setCancelable(false);
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                quit();
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    public void quit() {
        super.finish();
    };

Upvotes: 14

Related Questions