如何在jetpack撰写中授予权限后自动执行操作?



我有一个按钮来激活系统摄像头的意图在我的应用程序。我想实现一个权限逻辑,因为它通常是这样做的。

  1. 当第一次启动应用程序时,按下该按钮会导致默认的权限请求对话框。
  2. 如果允许,将立即激活系统摄像头。
  3. 如果没有,它将重新请求。
  4. 如果第二次被拒绝,对话框将永远不会弹出。(这是Android的默认逻辑)
  5. 但是,如果用户一直点击这个按钮,它会出现一个对话框,询问用户是否要链接到这个应用程序的权限设置表。

现在,我的仍然缺少特性2和5。它不会自动进入相机。而我不知道如何实现5.

这是我的代码。

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CameraButton(context: Context = LocalContext.current) {
val permissionState = rememberPermissionState(
permission = Manifest.permission.CAMERA,
)
Button(
onClick = {
if (permissionState.status.isGranted) {
context.startActivity(Intent(MediaStore.ACTION_IMAGE_CAPTURE))
}
else {
permissionState.launchPermissionRequest()
if (permissionState.status.isGranted) {
context.startActivity(Intent(MediaStore.ACTION_IMAGE_CAPTURE))
}
}
},
modifier = Modifier.size(90.dp, 60.dp)
) {
Icon(painter = painterResource(id = R.drawable.camera), contentDescription = null)
}

if (permissionState.status.shouldShowRationale) {
AlertDialog(
onDismissRequest = {},
title = {
Text(
text = "Permission Request",
style = TextStyle(
//fontSize = MaterialTheme.typography.h6.fontSize,
fontWeight = FontWeight.Bold
)
)
},
text = {
Text("Taking photos requires camera permission to run.")
},
confirmButton = {
Button(onClick = {permissionState.launchPermissionRequest()}) {
Text("Give Permission")
}
}
)
}
}

要存档5点,你需要保存布尔属性,当你已经使用SharedPreferencesJetpack Datastore请求权限时,因为没有其他方法知道权限被永久拒绝

要存档2点,您需要做如下操作:

val cameraPermissionState = rememberPermissionState(permission = android.Manifest.permission.CAMERA)
LaunchedEffect(key1 = cameraPermissionState){
if (cameraPermissionState.status.isGranted) openCamera()
}
cameraPermissionState.launchPermissionRequest()

编辑1

避免在不点击按钮的情况下打开相机的完整代码:

val context = LocalContext.current
val cameraPermissionState = rememberPermissionState(permission = CAMERA_PERMISSION)
var permissionRequested: Boolean by rememberSaveable { mutableStateOf(false) }
if (permissionRequested && cameraPermissionState.status.isGranted) {
permissionRequested = false
navigateToQrCodeScanner()
}
Button(
onClick = {
when {
cameraPermissionState.status.isGranted -> {
navigateToQrCodeScanner()
}
cameraPermissionState.status.shouldShowRationale -> {
saveCameraPermissionRationaleShown()
showCameraPermissionRationaleAlert(false) {
permissionRequested = true
cameraPermissionState.launchPermissionRequest()
}
}
cameraPermissionRationaleAlreadyShown -> {
showCameraPermissionRationaleAlert(true) { context.navigateToAppSettings() }
}
else -> {
permissionRequested = true
cameraPermissionState.launchPermissionRequest()
}
}
}
...
)

showCameraPermissionRationaleAlert是可组合函数的参数:

showCameraPermissionRationaleAlert: (Boolean, (() -> Unit)) -> Unit

其中boolean是表示权限已被永久拒绝的属性,lambda是单击弹出按钮时要采取的动作。

相关内容

  • 没有找到相关文章

最新更新