Friday, 16 December 2016

Android: Implement "Press BACK again to exit"

You might have noticed a pattern in many android applications these days in which on pressing the back button to exit the application it gives you a message which says "Please press BACK again to exit" .
This post is regarding implementing this feature in your android app.
To implement this, you just need to do the following things:

1. In your activity in which you want to implement this feature, add a variable as follows:
                         
                                 private boolean isBackPressedOnce = false;  

2. Now add the following code in the onBackPressed() method of your activity as follows:

    @Override
    public void onBackPressed() {
            if (isBackPressedOnce) {
                super.onBackPressed();
                return; // exit the appliactaion
            }

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

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isBackPressedOnce = false;
                    // Runnable to change the value of variable isBackPressedOnce to true after 2 
                    // seconds if you take more than 2 seconds of time in pressing the back button again.
                }
            }, 2000);

    }

That's all. Now on pressing the back button in your app it will show you the message "Please press BACK again to exit".

Share & comment if any issues.


No comments:

Post a Comment