Search code examples
javaandroidxmlandroid-alertdialog

How to show AlertDialog even if Activity is on background?


I have an AlertDialog and I want to show it even if the user is visiting another activity.

This is AlertDialog:

AlertDialog.Builder builder = new AlertDialog.Builder(context.getApplicationContext());

    builder.setMessage("Message").setCancelable(
            false).setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    
                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            
        }
    });
    AlertDialog alert = builder.create();
    alert.show();

Solution

  • You can create a method in utils class and pass context, so that you can use dialog in required class, but precaution need to take with life cycles to avoid memory leaks.