Search code examples
androidandroid-alertdialogandroid-lifecycle

How to display an AlertDialog before activity onDestroy, and before the application is closed by user?


My active Activity runs a bound/unbound service, which is an essential part of the application. I want to display an AlertDialog when the user attempts to close the app when the said Activity and the service is running. I understand that this is not in lines with good UX design, but the functionality is essential and non-resumable, so a user confirmation is required at this step.

I'm already overriding the following method.

@Override
public void onBackPressed() {
    //Handle AlertDialog here.
    //Activity must not stop + Application must not close without user confirmation.
}

I need to display the AlertDialog in two other conditions besides Back button:

  1. The app is in the background (with the foreground service running), and a user tries to kill the apps, e.g. clears all apps from carousel, or clears this app, etc.
  2. The app is in the foreground and the user closes the app using Recents button.

PS: Are there different methods to support gestures instead of B-H-R buttons?


Solution

  • So it is the android functionality which you can not override. For back button only you can implement the dialog box, not for other two keys which are mend to take your app in taskbar or go to home

    Create the method exitByBackKey()

            AlertDialog alertbox = new AlertDialog.Builder(this)
                    .setMessage("Do you want to exit application?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {
                            System.exit(0);
                            //close();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {
                            //nothing
                        }
                    })
                    .show();
        }
    

    And now under your onBackPressed() call this method.

    @Override
    public void onBackPressed() {
        //Handle AlertDialog here.
        //Activity must not stop + Application must not close without user confirmation.
         exitByBackKey()
    }