Message when user is exiting application

Asked

Viewed 988 times

1

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

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

2 answers

2

This type of approach is not recommended. First because both the back button as to the finish do not guarantee that the app is being terminated (the system decides whether to terminate an app or just leave it in the background). And second that you should already process all the data you want to persist in the event onStop.

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

@Override
public void onBackPressed() {
  //crie seu alert
}
  • The intention was for onDestroy() to stop the stream, only when closing the application, I was going to put inside this type of argument. Not to stop when you just leave class.

0

To complement the response of Androiderson, you can do so:

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 is how it works:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.