I am working with an app on AndroidStudio. What code could I implement for when the back is called to leave the app to let me know if I want to leave it or not?
I am working with an app on AndroidStudio. What code could I implement for when the back is called to leave the app to let me know if I want to leave it or not?
Basically you have to overwrite the onBackPressed
of the Activity
method:
private int backpress = 0;
@Override
public void onBackPressed(){
backpress++; // La primera vez es 1 (aviso), la segunda es 2 (finish)
if (backpress > 1) {
this.finish();
} else {
Toast.makeText(getApplicationContext(), "Pulse de nuevo para salir.", Toast.LENGTH_SHORT).show();
}
}
You can reset the variable backpress
so that you can ask for the "press again" after X time by adding the following code within the onBackPressed
method:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
backpress = 0;
}
}, 3000); // Resetea a los 3 segundos