【问题标题】:How to execute an action automatically after permission granted in jetpack compose?如何在 Jetpack Compose 授予权限后自动执行操作?
【发布时间】:2023-01-23 20:48:24
【问题描述】:

我有一个按钮可以在我的应用程序中使用 Intent 激活系统摄像头。我想按照通常的方式实现权限逻辑。

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

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

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

    要存档 2 点,您需要执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2011-09-25
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2016-05-02
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多