如何使用 Jetpack Compose 请求权限?

Mat*_*zuk 10 android android-jetpack-compose

应该如何实现从 Jetpack Compose View 请求许可?我正在尝试使用 Jetpack Compose 实现访问相机的应用程序。我尝试了如何在 Jetpack Compose 中获取当前状态或上下文的示例 不幸的是,示例不再适用于 dev06。

        fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
            ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 15

作为compose_version = '1.0.0-beta04'

implementation 'androidx.activity:activity-compose:1.3.0-alpha06'
Run Code Online (Sandbox Code Playgroud)

您可以像这样简单地请求许可:

@Composable
fun ExampleScreen() {
    val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            // Permission Accepted: Do something
            Log.d("ExampleScreen","PERMISSION GRANTED")

        } else {
            // Permission Denied: Do something
            Log.d("ExampleScreen","PERMISSION DENIED")
        }
    }
    val context = LocalContext.current

    Button(
        onClick = {
            // Check permission
            when (PackageManager.PERMISSION_GRANTED) {
                ContextCompat.checkSelfPermission(
                    context,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) -> {
                    // Some works that require permission
                    Log.d("ExampleScreen","Code requires permission")
                }
                else -> {
                    // Asking for permission
                    launcher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
                }
            }
        }
    ) {
        Text(text = "Check and Request Permission")
    }
}

Run Code Online (Sandbox Code Playgroud)

  • `PackageManager.PERMISSION_GRANTED` 是一个 `static final int 0`,所以 when 是 `when (0)`。那是对的吗?看起来when条件和第一个匹配需要交换? (2认同)

Naf*_*bbo 15

谷歌有一个名为“Accompanist”的库。它有许多帮助库,其中之一就是权限库。

检查:图书馆: https: //github.com/google/accompanist/

文档: https: //google.github.io/accompanist/permissions/

例子:

在 build.gradle 文件中设置:

repositories {
    mavenCentral()
}
Run Code Online (Sandbox Code Playgroud)

依赖项{

implementation "com.google.accompanist:accompanist-permissions:<latest_version>"
Run Code Online (Sandbox Code Playgroud)

}

代码实现

@Composable
private fun FeatureThatRequiresCameraPermission() {

    // Camera permission state
    val cameraPermissionState = rememberPermissionState(
        android.Manifest.permission.CAMERA
    )

    when (cameraPermissionState.status) {
        // If the camera permission is granted, then show screen with the feature enabled
        PermissionStatus.Granted -> {
            Text("Camera permission Granted")
        }
        is PermissionStatus.Denied -> {
            Column {
                val textToShow = if (cameraPermissionState.status.shouldShowRationale) {
                    // If the user has denied the permission but the rationale can be shown,
                    // then gently explain why the app requires this permission
                    "The camera is important for this app. Please grant the permission."
                } else {
                    // If it's the first time the user lands on this feature, or the user
                    // doesn't want to be asked again for this permission, explain that the
                    // permission is required
                    "Camera permission required for this feature to be available. " +
                        "Please grant the permission"
                }
                Text(textToShow)
                Button(onClick = { cameraPermissionState.launchPermissionRequest() }) {
                    Text("Request permission")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


mr.*_*uss 8

查看 Google Accompanist 的Jetpack Compose 权限

请记住,在撰写本文时,该 API 仍被认为是实验性的,使用时将需要@ExperimentalPermissionsApi注释。


小智 7

/**
 * Composable helper for permission checking
 *
 * onDenied contains lambda for request permission
 *
 * @param permission permission for request
 * @param onGranted composable for [PackageManager.PERMISSION_GRANTED]
 * @param onDenied composable for [PackageManager.PERMISSION_DENIED]
 */
@Composable
fun ComposablePermission(
    permission: String,
    onDenied: @Composable (requester: () -> Unit) -> Unit,
    onGranted: @Composable () -> Unit
) {
    val ctx = LocalContext.current

    // check initial state of permission, it may be already granted
    var grantState by remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(
                ctx,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        )
    }
    if (grantState) {
        onGranted()
    } else {
        val launcher: ManagedActivityResultLauncher<String, Boolean> =
            rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission()) {
                grantState = it
            }
        onDenied { launcher.launch(permission) }
    }
}
Run Code Online (Sandbox Code Playgroud)