Search code examples
androidkotlinandroid-jetpack-composeandroid-permissions

Problem Requesting Notification Permissions in Compose


I am trying to request the Notification Permission in a Composable.

I've been following online examples, and I can't get it to work. However, the same code, when requesting the Camera permission instead, works as expected, and I don't know why. And yes, the permission is in my manifest, and the notifications do work.

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun Foo() {
    val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
            println("permission granted")
        } else {
            println("permission not granted")
        }
    }
    val context = LocalContext.current
    NotificationButton(
        onClick = {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
                 // permission granted
            } else {
                launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    )
}

Solution

  • OP clarified that they saw "permission granted" when clicking the button.

    This meant that the permission launcher was being called and returning "granted".

    The POST_NOTIFICATIONS permission was introduced in SDK 33 (Tiramisu).

    If the application were run in SDK < 33 (on an emulator or physical device), the SDK doesn't know about the permission, and the checkSelfPermission call would just return "granted".

    When running with SDK >= 33, the only way to get to that "permission granted" path is if the launcher were run and returned granted status.

    You can verify this by looking at the app info (Settings > Apps > Your App > Permissions) and see if the Notifications permission has been allowed.

    You can either uncheck that permission or uninstall the application. (When developing and testing permissions, I usually find it faster to uninstall and re-run. (You can also revoke permissions via adb).