How do I display dialog from a service?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
Material styled Dialog from a Service
From a Service, you can easily show a Material Design styled Dialog manipulating its Window type, attributes and LayoutParams.
Before we begin: AppCompat Library
This guide presumes you are using Android AppCompat libray.
Before we begin: Permissions
This method needs the SYSTEM_ALERT_WINDOW permission. Usually a Service that wants to display a Dialog also has some Views drawn over the system UI (added using
WindowManager.addView()
method) so you might have already declared this permission usage inside you manifest. If not, add this line:In Android 6.0 Marshmallow, the user must explicitly allow your app to "draw over other apps". You can programmatically start the system settings Activity that contains the switch:
Create your custom Material Design Dialog theme
Inside
themes.xml
create this theme and customize it with your app colors:Launch your Dialog
Inside your Service:
firstable you need to cast your Activity in Service so in your Activity add
and in On create add this
and when we move to your Service alse declare this :
and in on Create service this is our casting
and the alert dialog will be look like this :
remember that
mact
is the Cast class to use in Alert Builder ...that works fine for me hope it help .The documentation suggests that you should make use of notifications. Re-evaluate why you might need to use dialogs. What are you trying to achieve?
Another way without using an activity:
Please note that you have to use this permission:
I am calling the below, inside the service when I need to show a dialog.
Make sure you have the below permission added to the manifest. android.permission.SYSTEM_ALERT_WINDOW
I also think that for SDK 23 and above, the user should explicitly set the "Draw over other Apps" permission from the Application manager for the App that starts this service.
android-smspopup does exactly that.
A service receives a sms and it starts an
Activity
with:EDIT: The dialog activity is started here with this code
With
getPopupIntent()
declared as followed (code here):SmsPopupActivity
class obviously defines the dialog activity. Its declared as followed inAndroidManifest.xml
: