如何从 Android Marshmallow 中的服务请求权限 [英] How to request permissions from a Service in Android Marshmallow
问题描述
在 Android Marshmallow 中,应在需要时在运行时请求权限,而不是在安装应用时一次性请求所有权限.但是,我似乎只能从 Activity 请求权限,这是一个问题,因为我的应用程序仅包含服务.(你可能会问这是为什么?该应用程序内置了一个 Android Wear 表盘,手机所做的只是查找附近的照片并将其发送到手表 - 不需要 Activity.但它确实需要位置权限.)>
那么,有没有办法向服务请求权限?或者像过去一样强制在安装时授予权限?
requestPermission()
只能从 Activity
而不是 Service
调用code>(不像 checkPermission()
只需要 PackageManager
).所以你需要做一些额外的工作来解决这个问题;你确实需要在你的应用程序中提供一个 Activity
,例如,你的 Service
可以检查它需要的权限,如果它们还没有被授予,它可以创建一个通知,可以通过描述性的短消息通知用户为什么会有通知以及当他们点击通知时需要发生什么等.
In Android Marshmallow, permissions should be requested at runtime when they are needed, instead of all at once when an app is installed. However, I can only seem to request permissions from an Activity, which is a problem since my app contains only Services. (Why is that, you might ask? The app has an Android Wear watch face bundled inside, and all the phone does is look up photos nearby to send to the watch - no Activity needed. But it does require location permissions.)
So, is there any way to request permissions from a Service? Or somehow force the permissions to be granted at install time as in the past?
requestPermission()
can only be called from an Activity
and not a Service
(unlike checkPermission()
that only requires PackageManager
). So you need to do some extra work to get around that; you do need to provide an Activity
in your app and, for example, your Service
can check for permissions it needs and if they have not been granted yet, it can create a notification and that can inform user with a descriptive short message as to why there is a notification and what needs to happen when they click on the notification, etc.
这篇关于如何从 Android Marshmallow 中的服务请求权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!