如何从Android棉花糖中的服务请求权限 [英] How to request permissions from a Service in Android Marshmallow

查看:79
本文介绍了如何从Android棉花糖中的服务请求权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android Marshmallow中,应在需要时在运行时请求权限,而不是在安装应用程序时立即请求所有权限.但是,我似乎只能向活动请求权限,这是一个问题,因为我的应用仅包含服务. (为什么会这样,您可能会问?该应用程序捆绑了一个Android Wear表盘,并且所有手机所做的只是查找附近的照片以发送至手表-无需进行活动".但它确实需要位置权限.)

那么,有什么方法可以向服务请求权限吗?还是以某种方式强制像过去一样在安装时授予权限?

解决方案

requestPermission()只能从Activity而不是Service调用(不同于仅需要PackageManagercheckPermission()).因此,您需要做一些额外的工作来解决此问题;您确实需要在应用程序中提供一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆