如何在 Android M 中向服务请求权限

在 Android M 中,应该在需要权限时在运行时请求权限,而不是在安装应用程序时一次性请求所有权限。然而,我似乎只能请求一个活动的权限,这是一个问题,因为我的应用程序只包含服务。(你可能会问,这是为什么?这个应用程序有一个安卓穿戴手表表面捆绑在内,所有的手机做的就是查找附近的照片发送到手表-没有活动需要。但它确实需要位置权限。)

那么,有没有办法从服务请求权限呢?或者像过去一样在安装时强制授予权限?

68212 次浏览

I agree, this is very troublesome for services, I think you should report an issue on Android Developer Preview page for this.

At the moment, I think the best solution is to check for permission on service, and show notification if the permission is missing. Even better, create an DialogActivity to request for permission when users press on the notification.

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.

You can use ResultReceiver to create a receiver of the users answer, then pass it as callback to the Activity, through notification's PendingIntent. Reference

Have a look at PermissionEverywhere library. It allows you to request permission from any context.

It creates a notification clicking on which it opens up an activity asking for permission.

Sample code from library's github page:-

@Override
protected Boolean doInBackground(Void... params) {
PermissionResponse response = PermissionEverywhere.getPermission(getApplicationContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQ_CODE,
"Notification title",
"This app needs  a write permission",
R.mipmap.ic_launcher)
.call();
//waits..
boolean isGranted = response.isGranted();


if(isGranted){ //changed from isGrante to isGranted
// Do stuff
}
}

There is a very simple library that allows doing exactly this. You can check for permissions from anywhere (even from a service), based on whether the app is in foreground or background, it either shows normal dialog or generates a notification asking for permissions. The code is really easy to understand and it's really easy to use too.

Do give it a try: Android Permissions