Search code examples
androidkotlin

requestPermissionLauncher does not show a dialog for permission


So I try to use the new way for requesting permissions (Allow the system to manage the permission request code) like written https://developer.android.com/training/permissions/requesting#allow-system-manage-request-code here. When I tap on camera button I just got "Permission Denied", but I don't get a window with actual permission request (where I can allow or deny it). In the documentation is written "To display the system permissions dialog when necessary, call the launch() method on the instance of ActivityResultLauncher that you saved in the previous step." What do I do wrong? What do I miss?

under onViewCreated I have:

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)
                }
            }
    }  

And I have this piece of code:

// 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()
    }
}

Solution

  • If you are running on Android 10 (API 29) add the following line in the manifest:

    android:requestLegacyExternalStorage="true"