如何从Android棉花糖中的服务请求权限 [英] How to request permissions from a Service in Android Marshmallow
问题描述
在Android Marshmallow中,应在需要时在运行时请求权限,而不是在安装应用程序时立即请求所有权限.但是,我似乎只能向活动请求权限,这是一个问题,因为我的应用仅包含服务. (为什么会这样,您可能会问?该应用程序捆绑了一个Android Wear表盘,并且所有手机所做的只是查找附近的照片以发送至手表-无需进行活动".但它确实需要位置权限.)>
那么,有什么方法可以向服务请求权限吗?还是以某种方式强制像过去一样在安装时授予权限?
requestPermission()
只能从Activity
而不是Service
调用(不同于仅需要PackageManager
的checkPermission()
).因此,您需要做一些额外的工作来解决此问题;您确实需要在应用程序中提供一个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棉花糖中的服务请求权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!