我想使用以下代码检查应用程序启动时的所有权限:
public void checkPermissions() {
List<String> permissions = new ArrayList<>();
permissions.add(Manifest.permission.INTERNET);
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
List<String> deniedPermissions = new ArrayList<>();
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
deniedPermissions.add(permission);
}
}
if (deniedPermissions.size() > 0) {
Activity activity = (Activity) context;
ActivityCompat.requestPermissions(activity, deniedPermissions.toArray(new String[deniedPermissions.size()]), PERMISSIONS);
}
}
如果用户接受权限,则会调用此代码:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MainController.PERMISSIONS:
boolean allPermissionsGranted = true;
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED)
allPermissionsGranted = false;
}
if (!allPermissionsGranted) {
View view = findViewById(R.id.content_main);
Snackbar snackBar = Snackbar.make(view, "YOLO", Snackbar.LENGTH_LONG);
}
break;
}
}
但如果他拒绝,则没有任何反应,onRequestPermissionsResult函数永远不会被调用。
我做错了吗?
答案 0 :(得分:1)
好的,我通过实现接口ActivityCompat.OnRequestPermissionsResultCallback