1
votes

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);
    }
1
you never see toast message? - an_droid_dev
@MikeM. i have added my attempt thank you - jjjjjjjjjjjjjjjjj
@an_droid_dev i see the message but when i click the second time it refreshes/restarts my app instead of closing it down, i then press it again twice and it exits from the restarted app? - jjjjjjjjjjjjjjjjj
have you initialize doubleBackToExitPressedOnce = false ? - Satan Pandeya
@SatanPandeya yes - jjjjjjjjjjjjjjjjj

1 Answers

2
votes

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