如何向服务请求权限

4

我正在尝试在我的服务(Service)上请求权限。通常,我需要传递一个Activity来请求权限。但是我的应用程序没有Activity

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {    
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);
    }
}

我该如何从服务中完成它?

我为什么被踩了?这是一个合理的问题。请解释一下,如果我错了,我会很乐意删除我的问题。 - Blue Nite
1个回答

1

向服务请求权限是没有意义的。请注意,当应用程序需要访问某些系统功能时,您需要在活动中请求用户的权限,然后启动服务。


如果您发现您的服务在启动后某个时刻缺少了权限,例如由JobScheduler触发了该服务,则您可以发出一个通知(Notification),以提示用户授予您权限,然后安静地关闭您的服务。 - CommonsWare
我的应用程序没有“Activity”。 - Blue Nite
“向服务请求权限没有意义。”由于我的应用程序没有“Activity”,因此在“Service”中请求是否有意义。 - Blue Nite
4
@BlueNite: "由于我的应用程序没有 Activity",那么你会遇到更大的问题。除非它预装在某些设备上或作为其他应用程序的插件,否则您的应用程序将永远不会运行。需要使用显式的 Intent 来启动你的组件;在此之前,你的清单注册的接收器将不起作用,也没有其他东西会启动你的服务。 - CommonsWare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接