Sagar Rawal
Sagar Rawal

Reputation: 399

Intercept back button to Go back to previous page if pressed once and exit if twice

I've been working in an android app which contain mainly local html pages with only one Mainactivity. I'm using this code to exit the app which when pressed twice will exit the app. For example I have two html files inside assets folder and one page link to other. If I have gone from A to B , then if back button is pressed once..it should redirect me to previous page and if pressed twice will exit the app. For now code I'm using to exit the app if pressed twice is...

boolean doubleBackToExitPressedOnce = false;

@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);

}

I would like to implement method if pressed once will redirect to previous page and if pressed twice will exit the app. Any help would be much appreciated.

Upvotes: 1

Views: 476

Answers (1)

zeekhuge
zeekhuge

Reputation: 1594

You can achieve it like this :

boolean doubleBackToExitPressed = false;
long lastBackPressTime = 0;

@Override
public void onBackPressed() {
    // assuming the gap between two presses is 500ms
    long currentTime = System.currentTimeMillis();
    if (currentTime - lastBackPressTime < 500) {
        doubleBackToExitPressed = true;
        super.onBackPressed();
        return;
    } else {
        lastBackPressTime = System.currentTimeMillis();
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    }

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!doubleBackToExitPressed) {
                 // go to the previous webpage
            } else {
                doubleBackToExitPressed = false;
            }
        }
    }, 510); // trigger this after 510 milli seconds
}

In this code, on the first back-press, the current time is saved, and on the second back-press, its compared with lastBackPressTime. If the gap is less than 500 milli seconds, the super.onBackPressed() is called.

The code inside the handler triggers after 510 milli seconds, and checks if doubleBackToExitPressed is false.

Upvotes: 1

Related Questions