0

I am creating an app which requires an alert dialog to pop up from a class that is not an activity. I tried creating one with the help of a AlertDialog builder and passed the context in, but the app stops working whenever I try to show the alert. When I used the same method to create an AlertDialog in the main activity it worked, but if I do that, it will not pop up at the time I want it to. Is there anyway I can make an AlertDialog from a class that is not an activity? Or I can access the activity reference from the class so that I can use it to create the alert?

Please note that the class is created as a result of a service, and not using the constructer directly from the main activity, so I cannot pass the main activity reference through the constructor. Currently I have put a notification in place of the alert, but I would much rather have an alert than a notification.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

0

There is a reason why notifications are currently the supported method of notifying the user of something from a servce. If you want to know more about why you shouldn't use them then check out this answer. If that doesn't make you rethink using a dialog in this situation then here's how to show one from a service.

First you need to build a dialog:

AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("Title")
                    .setMessage("Message")
                    .create();

alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

Then add this permission:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Community
  • 1
  • 1
MrEngineer13
  • 38,642
  • 13
  • 74
  • 93