2017-04-09 56 views
-1

我想请求我的服务的许可。通常要申请一个权限,我必须传递一个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); 
    } 
} 

我该如何从服务中做到这一点?

+0

我怎么被低估?这是一个有效的问题。请解释一下,如果我错了,我会很乐意删除我的问题。 –

回答

2

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

+0

如果你发现你的服务在启动后有一段时间没有权限 - 例如,服务被“JobScheduler”启动 - 你可以提出一个'Notification'来提示用户授予你许可权,然后悄悄关闭你的服务。 – CommonsWare

+0

我的应用程序没有“活动”。 –

+0

“请求获得服务许可没有任何意义。”由于我的应用程序没有“Activity”,因此我在“Service”中请求它是有意义的。 –