我在Android M中使用anroid应用并需要一些权限才能访问CAMERA
,RECORD_AUDIO
,WRITE_EXTERNAL_STORAGE
,...所以我在用户打开时检查我的权限应用程序在第一次。但是如果用户否认它,我如何自动检测到用户正在使用需要权限的功能然后再次询问它们?或者我必须将我的条件放在需要许可的每个功能中。
我知道当我们使用某些需要权限的功能但不允许时它会抛出异常,那么我们是否有任何类来处理这个任务?
答案 0 :(得分:1)
我使用这个逻辑:每个Activity都扩展了一个BaseActivity,其中有一个方法可以在每次调用onCreate()时检查权限。
我使用的方法是:
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
因此,每次用户启动新的Activity时,应用程序都会检查权限并显示尚未授予的权限。
要管理结果,请使用onRequestPermissionsResult()
如果您只想向用户询问需要权限的功能,则必须在每项活动中进行检查
答案 1 :(得分:0)
onRequestPermissionsResult你可以检查特定权限是否被授予你可以从那里再次调用权限对话框如果没有为例子授予特定权限
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA) {
// BEGIN_INCLUDE(permission_result)
// Received permission result for camera permission.
Log.i(TAG, "Received response for Camera permission request.");
// Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Camera permission has been granted, preview can be displayed
Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
Snackbar.make(mLayout, R.string.permision_available_camera,
Snackbar.LENGTH_SHORT).show();
} else {
Log.i(TAG, "CAMERA permission was NOT granted.");
// Ask again for permission
}
// END_INCLUDE(permission_result)
} else if (requestCode == REQUEST_CONTACTS) {
Log.i(TAG, "Received response for contact permissions request.");
// We have requested multiple permissions for contacts, so all of them need to be
// checked.
if (PermissionUtil.verifyPermissions(grantResults)) {
// All required permissions have been granted, display contacts fragment.
Snackbar.make(mLayout, R.string.permision_available_contacts,
Snackbar.LENGTH_SHORT)
.show();
} else {
Log.i(TAG, "Contacts permissions were NOT granted.");
// Ask again for permission
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}