Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prompt user when Back button is pressed

Which is the good place to ask user, whether (s)he wants to exit the app when (s)he clicked the back button? I considered the onPause and onStop, but these methods fires whenever app is gone behind the other apps.

Update: The app should also ask if user is trying to exit the app from a button (in app itself), not the Back hard key.

like image 775
Chromium Avatar asked Jun 09 '11 09:06

Chromium


People also ask

What happens when browser Back button is pressed?

Your browser keeps a stack of records showing which pages you've visited in the current window's session. When you press the back button on your browser, it goes to the last page in that stack.

How do you code a back button?

You can use the history. back() method to tell the browser to go back to the user's previous page. One way to use this JavaScript is to add it to the onclick event attribute of a button.

How does JQuery handle browser back button?

How do I get the browser back button event in JQuery? You can simply fire the “popState” event in JQuery e.g: $(window). on('popstate', function(event) { alert(“pop”); });


1 Answers

Ask for user's permission to close the app.

You can do it in the following way;

/**
 * Exit the app if user select yes.
 */
private void doExit() {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            AppDemoActivity.this);

    alertDialog.setPositiveButton("Yes", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });

    alertDialog.setNegativeButton("No", null);

    alertDialog.setMessage("Do you want to exit?");
    alertDialog.setTitle("AppTitle");
    alertDialog.show();
}

Which is the good place to ask user, whether (s)he wants to exit the app when (s)he clicked the back button?

Since, you want to prompt user when (s)he clicked the back hard button, as suggested by others, you can override the onBackPressed() method and call the above method from there;

@Override
public void onBackPressed() {

    doExit();
}

As suggested by @Martyn, you can use the onKeyDown to achieve the same;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if(keyCode == KeyEvent.KEYCODE_BACK) {
        doExit();
    }

    return super.onKeyDown(keyCode, event);
}

The app should also ask if user is trying to exit the app from a button (in app itself), not the Back hard key.

For this, call the doExit() from your button's onClick;

Button exitButton = (Button)findViewById(R.id.exitButton);
exitButton.setOnClickListener(new android.view.View.OnClickListener() {

    @Override
    public void onClick(View v) {
        doExit();
    }
});


Related Info:

  • Implementing effective navigation
like image 107
Mudassir Avatar answered Nov 09 '22 02:11

Mudassir