Android Fragments Android API 21位置权限条件在接受对话框结果之前为true

nwlls2ji  于 2023-08-06  发布在  Android
关注(0)|答案(1)|浏览(125)

我改变了以下方法

public static boolean requestForLocationPermission(Fragment fragment) {
String LOCATION_PERMISSION = Manifest.permission.ACCESS_FINE_LOCATION;
     if (ContextCompat.checkSelfPermission(fragment.requireContext(), LOCATION_PERMISSION)
                    == PackageManager.PERMISSION_GRANTED)
                return true;
    
            if (ActivityCompat.shouldShowRequestPermissionRationale(fragment.requireActivity(), LOCATION_PERMISSION)) {
                PermissionDialog.showForResult(fragment, LOCATION_PERMISSION_REQUEST_CODE, LOCATION_PERMISSION);
            } else {
                fragment.requestPermissions(new String[]{LOCATION_PERMISSION}, LOCATION_PERMISSION_REQUEST_CODE);
            }
            return false;
}

字符串
在我发现自动位置检测在API 21上不起作用之后,主要是因为fragment.requestPermissions被弃用:

public static boolean requestForLocationPermission(Fragment fragment) {

String LOCATION_PERMISSION = Manifest.permission.ACCESS_FINE_LOCATION;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(fragment.requireContext(), LOCATION_PERMISSION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.d("request_Permission 23:", "has been granted!");
            return true;
        }
    } else {
        if (PermissionChecker.checkSelfPermission(fragment.requireContext(), LOCATION_PERMISSION)
                == PermissionChecker.PERMISSION_GRANTED) {
            Log.d("request_Permission 21:", "has been granted!");
            return true;
        }
    }
    if (ActivityCompat.shouldShowRequestPermissionRationale(fragment.requireActivity(), LOCATION_PERMISSION)) {
        PermissionDialog.showForResult(fragment, LOCATION_PERMISSION_REQUEST_CODE, LOCATION_PERMISSION);
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            fragment.requireActivity().requestPermissions(new String[]{LOCATION_PERMISSION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            ActivityCompat.requestPermissions(fragment.requireActivity(),
                    new String[]{LOCATION_PERMISSION},
                    LOCATION_PERMISSION_REQUEST_CODE);
            Log.d("request_Permission:", "has been requested ... ");
        }
    }
    return false;
}


添加这些Log行之后,对于logcat中的API 21来说,当权限对话框出现在屏幕上时,它显示的是request_Permission 21: has been granted!,而没有任何选项选择。
那么,为什么PermissionChecker.checkSelfPermission(fragment.requireContext(), LOCATION_PERMISSION) == PermissionChecker.PERMISSION_GRANTED对于API 21总是为真(可能对于API 22也是)?

bvn4nwqk

bvn4nwqk1#

运行时权限是在Android 6.0(API级别23)中随着Android Marshmallow的发布而引入的。在Android 6.0之前,权限是在安装时授予的,用户无法控制各个权限。
从Android 6.0开始,用户可以在运行时授予或拒绝个人权限,从而使他们能够更好地控制自己的隐私,并允许开发人员在应用实际需要时请求权限。

相关问题