以申请消息通知权限为例:
现在manifest中声明权限
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
权限申请
@Composable
fun HomeScreen(modifier: Modifier = Modifier) {
//进入界面后,先判断是否授予权限
val context = LocalContext.current
var hasPermission by remember {
//33之前都有权限,33之后,需要授权
mutableStateOf(if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
} else true)
}
//制定权限授权后的操作,将结果赋予hasPermission
val permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { isGranted ->
hasPermission = isGranted
}
Box(
modifier = modifier
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
if(!hasPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//没有权限,显示获取权限按钮,启动permissionLauncher
Button(onClick = {
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}) {
Text(text = "Request permission")
}
} else {
Text(text = "Home screen") //已经获取权限了,正常显示主页
}
}
}
示例来自 pl 的关于deeplink 的时候,需要显示通知,在更高平台上需要动态获取权限