Android back button event with example

Android device back button is to navigate from current activity to previous activity. In that case we are using below code for handing event on back button.

Declare variable in class :

1. boolean doubleBackToExitPressedOnce = false;

2. put code after onCreate method on an activity.

@Override
 public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }

Share this

Related Posts

Previous
Next Post »