2017-04-09 49 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」中請求它是有意義的。 –