首页 > 解决方案 > requestPermissionLauncher 不显示权限对话框

问题描述

所以我尝试使用新的方式来请求权限(允许系统管理权限请求代码),比如这里写的https://developer.android.com/training/permissions/requesting#allow-system-manage-request-code . 当我点击相机按钮时,我只是得到“权限被拒绝”,但我没有得到一个带有实际权限请求的窗口(我可以允许或拒绝它)。在文档中写道“要在必要时显示系统权限对话框,请在您在上一步中保存的 ActivityResultLauncher 实例上调用 launch() 方法。” 我做错了什么?我想念什么?

在 onViewCreated 我有:

binding.camera.setOnClickListener{
        when {
            ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {
                // You can use the API that requires the permission.
                //startCamera()
                makeText(activity, "Start camera", LENGTH_SHORT).show()
            }
            shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) -> {
                // In an educational UI, explain to the user why your app requires this
                // permission for a specific feature to behave as expected. In this UI,
                // include a "cancel" or "no thanks" button that allows the user to
                // continue using your app without granting the permission.
                makeText(activity, "Camera is necessary to add content.", LENGTH_SHORT).show()
            }
            else -> {
                    // You can directly ask for the permission.
                    // The registered ActivityResultCallback gets the result of this request.
                    requestPermissionLauncher.launch(
                                    Manifest.permission.CAMERA)
                }
            }
    }  

我有这段代码:

// Permission
val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
    isGranted: Boolean -> if (isGranted){
        // Permission Accepted
        makeText(activity, "Permission Accepted.", LENGTH_SHORT).show()
    }
    else {
        // Permission Denied
        makeText(activity, "Permission Denied.", LENGTH_SHORT).show()
    }
}

标签: androidkotlin

解决方案


如果您在 Android 10 (API 29) 上运行,请在清单中添加以下行:

android:requestLegacyExternalStorage="true"

推荐阅读