在 Compose 中请求通知权限时出现问题

问题描述 投票:0回答:1

我正在尝试在可组合项中请求通知权限。

我一直在关注在线示例,但无法使其工作。但是,相同的代码在请求相机权限时会按预期工作,我不知道为什么。是的,权限在我的清单中,并且通知确实有效。

@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)
            }
        }
    )
}
android kotlin android-jetpack-compose android-permissions
1个回答
0
投票

OP 澄清说,他们在单击按钮时看到“已授予许可”。

这意味着正在调用权限启动器并返回“已授予”。

SDK 33(提拉米苏)中引入了 POST_NOTIFICATIONS 权限。

如果应用程序在 SDK 中运行 < 33 (on an emulator or physical device), the SDK doesn't know about the permission, and the checkSelfPermission call would just return "granted".

当使用 SDK >= 33 运行时,到达“已授予权限”路径的唯一方法是运行启动器并返回已授予的状态。

您可以通过查看应用程序信息(设置 > 应用程序 > 您的应用程序 > 权限)来验证这一点,并查看是否允许通知权限。

您可以取消选中该权限或卸载该应用程序。 (在开发和测试权限时,我通常发现卸载并重新运行会更快。(也可以通过adb撤销权限)。

© www.soinside.com 2019 - 2024. All rights reserved.