I want to end the activity when I double click the back button, what should I do?

Asked 2 years ago, Updated 2 years ago, 68 views

If you look at the games or applications on the Google Play Store, they don't end right away when you press Back, they float toast You end the activity only when you press the dialog twice in a row. I want to make it like this I don't think there's a method that provides such a function, and I don't know what to do, so I post a question on SQ. How shall I do it?

android java back-button

2022-09-21 18:17

1 Answers

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

You can paste this method into the activity.


2022-09-21 18:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.