Search code examples
androidback-button

Exit app on second back button click - Android


I have a Log in screen and on the log in screen i would like so that if you press the back button once nothing happens but if you press it a second time the app stops/exits, i have seen other questions on here but for me non of the solutions work ...

Any help would be appreciated thank you!

This is an attempt of mine however it doesnt exit on the second press it restarts the app and then when you click back twice again from this it then exits ... ;

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

Solution

  • Try this one:

    private static long sayBackPress;
    
    @Override
    public void onBackPressed() {
        if (sayBackPress + 2000 > System.currentTimeMillis()){
            super.onBackPressed();
        }
        else{
            Toast.makeText(MainActivity.this, "Press once again to exit!", Toast.LENGTH_SHORT).show();
            sayBackPress = System.currentTimeMillis();
        }
    }