问题
I figured that in M requestPermissions() can only be called by an Activity class. I have an app that has no UI screen. It runs as a background service. Does this mean that I have to put a spinner screen if checkSelfPermissions returns denied?
回答1:
I have an app that has no UI screen.
Then it will never run, unless it is preinstalled on an Android device or custom ROM, or it is a plugin to some other app. Otherwise, your app will remain in the stopped state forever. Pretty much every app distributed through normal channels, including the Play Store, needs an activity.
Does this mean that I have to put a spinner screen if checkSelfPermissions returns denied?
I do not know what "a spinner screen" is. AFAIK, the recommended pattern for a service needing a runtime permission that it does not have is to:
Raise a
Notification
, to let the user know that the service cannot do its work without this permission.Have the
Notification
trigger anActivity
that can callrequestPermissions()
. Optionally, this activity can haveTheme.Translucent.NoTitleBar
, so the only visible UI is the permission dialog.If
onRequestPermissionResult()
indicates that you have the permission, the activity can tell the service to go ahead (e.g., via a call tostartService()
), thenfinish()
itself. IfonRequestPermissionResult()
indicates that the user denied the permission, do whatever makes sense (e.g., show theNotification
again, gracefully shut down, suggest to the user that the user uninstall the app).
来源:https://stackoverflow.com/questions/34817807/can-a-service-request-for-permission-in-android-m