How to get confirmation when user leaves an application

Most of the time we have the need the control if an user leaves our application.
It can be the case when the user leaves the application before doing some operations (let’s say save information and so on) and we want to inform him that he’s leaving the app losing all the information.
Well, in android in the Activity class there is a method called onBackPressed() that is called when user press the back button.

So in our main Activity we can override this method and implements our logic before leaving the application.

public class TestBackActivity extends Activity {

.............

   @Override

   public void onBackPressed() {

     // We implements here our logic

   }
}

Let’s say we want to ask, simply, if the user is sure to leave the app, using an AlertDialog. We can create a method like that:

private void createDialog() {

    AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);

    

    alertDlg.setMessage("Are you sure you want to exit?");

    alertDlg.setCancelable(false); // We avoid that the dialong can be cancelled, forcing the user to choose one of the options

    

    alertDlg.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

      

      public void onClick(DialogInterface dialog, int id) {

               TestBackActivity.super.onBackPressed();

           }

    }

     );

     alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which) {

      // We do nothing

    }

    });

     alertDlg.create().show();
  }

Notice that in the positiveButton method we invoke TestBackActivity.super.onBackPressed() leaving to the Activity class the job to close (if necessary the app).

It is a mistake to force the appl to be closed, we can demand it to the OS that will close it if the resources are getting too small.

image

When the user press the back button we will get:

image