一、概念
二、使用 Accompanist Permissions
不同版本中,权限状态(如PermissionState)中获取属性的方法不同,例如在"0.23.1"中,通过 PermissionState.hasPermission 属性拿到是否通过的 Boolean 值,在"0.35.0-alpha"中,通过 PermissionState.status.isGranted 属性拿到。
|------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| | 单个权限 | 多个权限 |
| 添加权限 | @Composable fun rememberPermissionState( permission: String ): PermissionState | @Composable fun rememberMultiplePermissionsState( permissions: List<String> ): MultiplePermissionsState |
| 发起请求 | fun launchPermissionRequest(): Unit | fun launchMultiplePermissionRequest(): Unit |
| 权限回调 | @Composable fun PermissionRequired( permissionState: PermissionState, permissionNotGrantedContent: @Composable (() -> Unit), permissionNotAvailableContent: @Composable (() -> Unit), content: @Composable (() -> Unit), ) | @Composable fun PermissionsRequired( multiplePermissionsState: MultiplePermissionsState, permissionsNotGrantedContent: @Composable (() -> Unit), permissionsNotAvailableContent: @Composable (() -> Unit), content: @Composable (() -> Unit), ) |
2.1 添加依赖
Groovy
implementation "com.google.accompanist:accompanist-permissions:0.35.1-alpha"
2.2 单个权限申请
Kotlin
val permissionState = rememberPermissionState(
Manifest.permission.CAMERA
)
PermissionRequired(
permissionState = permissionState,
permissionNotGrantedContent = { //还未申请或点击了拒绝
Button(onClick = { permissionState.launchPermissionRequest() }) {
Text("点击申请")
}
},
permissionNotAvailableContent = { //点击了不再询问
Text("无权限")
}
) { //点击了通过
Text("已授予")
}
2.3 多个权限申请
Kotlin
val permissionState = rememberMultiplePermissionsState(
listOf(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
)
)
LaunchedEffect(Unit) {
permissionState.launchMultiplePermissionRequest()
}