Message when the user is exiting the application

1

I know I can use AlertDialog for this, but without creating a button, only when the user is pressing the back to exit does an alert appear? Type, when it comes out (this involves the Android system in the part that does it alone) would a "finish" that Android understand and picking from it would create arguments to be sure even it will quit?

Note: The intention was for onDestroy () to stop the stream, only when it is closing the application, I was going to put within this type of argument. Not to stop when you just leave the class.

    
asked by anonymous 24.12.2015 / 00:48

2 answers

2

This type of approach is not recommended. First, because both the back button and finish do not guarantee that the app is shutting down (the system decides whether to close an app or just leave it in the background). And second, you should already treat all the data you want to persist in the onStop event.

But if you still want to go that route, just use the onBackPressed method:

@Override
public void onBackPressed() {
  //crie seu alert
}
    
24.12.2015 / 01:13
0

To complement the answer from Androiderson , you can do this:

In the main activity, define the following:

// Tratamento do back

private boolean backPressedOnce = false;
private Handler backPressedHandler = new Handler();

private static final int BACK_PRESSED_DELAY = 2000;

private final Runnable backPressedTimeoutAction = new Runnable() {
    @Override
    public void run() {
        backPressedOnce = false;
    }
};

and in onBackPressed, do the following

public void onBackPressed() {

    // Back pressionado

    try {

            if (this.backPressedOnce) {

                // Finaliza a aplicacao

                finish();

                return;
            }

            this.backPressedOnce = true;

            Toast.makeText(this, "Pressione novamente para sair",
                     Toast.LENGTH_SHORT).show();

            backPressedHandler.postDelayed(backPressedTimeoutAction, BACK_PRESSED_DELAY);

}

This works like this:

  • If it is in the main activity, when giving back, the message is displayed, if you give a new back (within the time -> BACK_PRESSED_DELAY), the application terminates

  • If you work with fragments, you need to check if you are in the root fragment for this logic

01.05.2018 / 16:49