Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking the back button twice to exit an activity

I've noticed this pattern in a lot of Android apps and games recently: when clicking the back button to "exit" the application, a Toast comes up with a message similar to "Please click BACK again to exit".

I was wondering, as I'm seeing it more and more often, is that a built-in feature that you can somehow access in an activity? I've looked at the source code of many classes but I can't seem to find anything about that.

Of course, I can think about a few ways to achieve the same functionality quite easily (the easiest is probably to keep a boolean in the activity that indicates whether the user already clicked once...) but I was wondering if there's something already here.

EDIT: As @LAS_VEGAS mentioned, I didn't really mean "exit" in the traditional meaning. (i.e. terminated) I meant "going back to whatever was open before the application start activity was launched", if that makes sense :)

like image 963
Guillaume Avatar asked Dec 08 '11 12:12

Guillaume


People also ask

When a user kills an activity by tapping the back button method is called?

If you hit the back button, then your Activity is finished and is destroyed, always resulting in a call to onDestroy().

What happens when back button is pressed in Android?

However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states. But we do not want to lose this data. To retain the data, we need to override the back pressed method.


1 Answers

In Java Activity:

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(Looper.getMainLooper()).postDelayed(new Runnable() {                  @Override         public void run() {             doubleBackToExitPressedOnce=false;                                }     }, 2000); }  

In Kotlin Activity:

private var doubleBackToExitPressedOnce = false override fun onBackPressed() {         if (doubleBackToExitPressedOnce) {             super.onBackPressed()             return         }          this.doubleBackToExitPressedOnce = true         Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show()          Handler(Looper.getMainLooper()).postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)     } 

I Think this handler helps to reset the variable after 2 second.

like image 80
Sudheesh B Nair Avatar answered Sep 21 '22 15:09

Sudheesh B Nair