requestPermissionLauncher不显示权限对话框

3
我尝试使用新的权限请求方式(允许系统管理权限请求代码),如此处所述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()
    }
}

你可以在 else 后尝试使用 ActivityCompat.requestPermissions(这里放置相机请求)。我总是写这段代码,它能够正常工作。你可以尝试一下。同时,请检查你的清单文件中是否添加了权限,也许你忘记在清单文件中请求权限了。 - Barney Stinson
1个回答

0
如果您正在运行Android 10(API 29),请在清单文件中添加以下行:
android:requestLegacyExternalStorage="true"

这怎么能解决请求的权限是相机权限的问题呢?但令我惊讶的是,它确实起作用了!它确实解决了我完全相同的问题... - Mackovich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接