向Android M服务请求位置权限 [英] Request Location Permissions from a service Android M

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

问题描述

我使用的服务在启动时会启动,并开始检查位置更新.现在,由于使用Android M,我拒绝了权限弹出窗口上的位置访问功能,一旦手机启动,我的服务就会崩溃.

I am using a service that on boot starts up and begins to check for location updates. Once i deny location access on permission popup now thanks to Android M my service crashes once the phone boots up.

由于在这种情况下我没有任何活动,因此对requestPermissions()的调用返回了ClassCastException,因为我的服务Context无法转换为活动.

Since i have no activity in this case the call to requestPermissions() returns a ClassCastException as my service Context cannot be cast to an activity.

我的方法调用:

ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_COARSE_LOCATION);

到目前为止,是否有任何解决方案?还是我必须撤销服务权利以不在这种状态下运行.

Is there any solution so far to this OR do I have to revoke the service rights to NOT run in such a state.

推荐答案

您无法通过服务请求权限,因为服务未绑定到UI,所以这种做法很有意义.由于服务上下文不是活动,因此您得到的异常是有道理的.

You can not request permission via a service, since a service is not tied to a UI, this kind of makes sense. Since a service context is not an activity the exception you are getting makes sense.

您可以检查权限是否在服务中可用,并在活动中请求该权限(是的,需要活动).

You can check if the permission is available in a service and request the permission in an activity (yes you need an activity).

在服务中:

 public static boolean checkPermission(final Context context) {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
 }

和活动中:

private void showPermissionDialog() {
    if (!LocationController.checkPermission(this)) {
        ActivityCompat.requestPermissions(
            this,
            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
            PERMISSION_LOCATION_REQUEST_CODE);
    }
}

这篇关于向Android M服务请求位置权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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