[英]Is it possible to ask for runtime permissions from a library?
我們制作了一些客戶在他們的應用程序中實現的庫,現在我們正在尋求更新它們以支持 Android 6.0 新權限模型。
我的問題是是否有任何方法可以在運行時從我們的庫(主要是靜態類)請求危險權限,而不是要求客戶端在使用我們的庫之前請求這些權限。
我一直在搞亂它,但對我來說似乎不可能,看起來它必須由我們沒有的 Activity 制作。
我是對的還是有什么辦法可以做到?
提前致謝。
看起來它必須來自我們沒有的活動。
正確。 這是因為權限請求邏輯在很大程度上依賴於startActivityForResult()
和onActivityResult()
,它們被包裝以處理權限請求。
此外,請求權限需要與整個應用程序流緊密相關,而無UI的庫無法知道此時是否適合嘗試請求權限。
歡迎您通過ContextCompat.checkSelfPermission()
檢查您是否擁有該權限,因為它沒有UI。 因此,您可以使用它來檢查庫的入口點是否具有執行工作所需的權限,而不僅僅是讓SecurityException
或其他任何事情發生。
首先,我想告訴你運行時權限檢查到Android M,在運行時如果你想通過用戶授予權限,你需要一個總是在活動或片段上打開的用戶交互權限對話框(在主線程上)。
因此,您可以為您的功能創建方法,該方法是參數
public void yourMethod(Activty activity){
//條件適用於如下所示的權限檢查
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation 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 {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
// Now you can handle call back in your activity through overriding the method // onRequestPermissionsResult this method must be written in your activity class
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
yourMethod(YourActivity.this);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
// you can also call your method here but it may be create infinite loop if user deny run time permission
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Activity對象也可以通過創建參數化構造。 為方法創建接口。
您可以使用我的庫從任何地方請求權限。
https://github.com/nabinbhandari/Android-Permissions
您只需要傳遞Context
參數,就可以輕松地請求權限。 您甚至不必覆蓋 onRequestPermissionsResult
方法。
示例代碼:
Permissions.check(this/*context*/, Manifest.permission.CALL_PHONE, null,
new PermissionHandler() {
@Override
public void onGranted() {
//do your task.
}
});
只需這一小塊代碼,您就可以從任何地方請求權限!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.