我在我的应用程序中使用Android API lvl 23。当我检查相机权限时,ContextCompat.checkSelfPermission
始终返回0(== PackageManager.PERMISSION_GRANTED
)
我设法将其从ContextCompat
更改为ActivityCompat
。
这是我的代码:
public static boolean verify(Activity activity, final String[] PERMISSIONS, final int PERMISSIONS_REQUEST_ID) {
if (underAPI23())
return true;
String[] denyPermission = new String[PERMISSIONS.length];
int denyPermissionLength = 0;
boolean shouldShowRequest = false;
for (int i = 0; i < PERMISSIONS.length; i++) {
int check = ContextCompat.checkSelfPermission(activity, PERMISSIONS[i]);
LogUtils.e(TAG, PERMISSIONS[i] + ": " + (check != PackageManager.PERMISSION_GRANTED));
// ===== ===== =====
// This always return true. :'(
// ===== ===== =====
if (check != PackageManager.PERMISSION_GRANTED) {
denyPermission[denyPermissionLength++] = PERMISSIONS[i];
if (shouldShowRequest == false) {
boolean should = ActivityCompat.shouldShowRequestPermissionRationale(activity, PERMISSIONS[i]);
if (should)
shouldShowRequest = true;
}
}
}
if (denyPermissionLength > 0) {
if (shouldShowRequest) {
ActivityCompat.requestPermissions(activity, denyPermission, PERMISSIONS_REQUEST_ID);
} else {
ActivityCompat.requestPermissions(activity, denyPermission, PERMISSIONS_REQUEST_ID);
}
return false;
} else {
return true;
}
}
我在Gradle build中的依赖关系
dependencies {
//...
compile 'com.android.support:support-v4:23.2.0'
compile 'com.android.support:appcompat-v7:23.2.0'
//...
}
更新:权限调用
if (PermissionGrant.verify(getActivity(), new String[]{Manifest.permission.CAMERA}, GRANT_TAKE_PHOTO)) {
// Do my jobs
}
答案 0 :(得分:3)
您的许可应为Manifest.permission.<Android permission>
你的Android目标版本是什么? shouldShowRequestPermissionRationale
总是返回false
,表示ContextCompat.checkSelfPermission(activity, permission)
总是在23岁以下的Android API lvl中返回false。
Document here。请关注:
注意:如果用户过去拒绝了权限请求并在权限请求系统对话框中选择了“不再询问”选项,则此方法返回false。如果设备策略禁止应用程序拥有该权限,则该方法也会返回false。