Notice to close app

2

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?

    
asked by PiledroMurcia 10.04.2017 в 10:16
source

1 answer

3

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
    
answered by 10.04.2017 / 10:25
source