作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
此程序需要访问相机和位置。但是,当设备需要同时请求这两种权限时,它只会请求其中一个权限,而不会请求另一个权限,直到我关闭我的程序然后重新打开它。我无法弄清楚这个问题。
protected void requestBoth() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA}, MULT_KEY);
}
protected void requestLoc() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCPERMISSION_KEY);
}
protected void requestCam() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMPERMISSION_KEY);
}
public void request() {
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) {
requestUpdates();
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
requestCam();
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
requestLoc();
} else {
requestBoth();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
request();
}
}
有人帮忙啊!顺便说一句,我故意从这个问题中排除了 shouldShowRequestPermissionsRationale 以及 onRequestPermissionsResult 方法,因为我认为这些与问题无关。 (我什至尝试将 request() 调用放在 onResume() 中,但是当权限被拒绝并且用户选中“不再显示”时,这会导致无限循环。我完全没有想法。
最佳答案
另一个有效的解决方案是使用 RxJava 和 RxPermission
所以你可以这样做:
rxPermissions
.requestEach(Manifest.permission.CAMERA,
Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(permission -> { // will emit 2 Permission objects
if (permission.granted) {
// `permission.name` is granted !
} else if (permission.shouldShowRequestPermissionRationale) {
// Denied permission without ask never again
} else {
// Denied permission with ask never again
// Need to go to the settings
}
});
或者您可以请求组合的每个权限:
rxPermissions
.requestEachCombined(Manifest.permission.CAMERA,
Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(permission -> { // will emit 1 Permission object
if (permission.granted) {
// All permissions are granted !
} else if (permission.shouldShowRequestPermissionRationale)
// At least one denied permission without ask never again
} else {
// At least one denied permission with ask never again
// Need to go to the settings
}
});
关于android - 我的程序一次只请求 1 个权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672385/
我是一名优秀的程序员,十分优秀!