Compose 如何申请权限

Compose Permissions 学习

废话不多说,今天我们一起学习一下在Compose中如何申请权限


1.jpg

首先导入依赖

repositories {
    mavenCentral()
}

dependencies {
    implementation "com.google.accompanist:accompanist-permissions:0.24.7-alpha"
}

使用

@Composable
fun PermissionPage() {
    PermissionPageContent()
}

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun PermissionPageContent() {
    //当前需要申请的权限
    val cameraPermissionState = rememberPermissionState(
        android.Manifest.permission.CAMERA
    )

    when (cameraPermissionState.status) {
        PermissionStatus.Granted -> {//已授权
            Text("Camera permission Granted")
        }
        is PermissionStatus.Denied -> {
            Column {
                val textToShow = if ((cameraPermissionState.status as PermissionStatus.Denied).shouldShowRationale) {
                    //如果用户拒绝了该权限但可以显示理由,那么请温和地解释为什么应用程序需要此权限(拒绝权限)
                    "The camera is important for this app. Please grant the permission."
                } else {
                    //如果这是用户第一次登陆此功能,或者用户不想再次被要求获得此权限,请说明该权限是必需的(用户选择拒绝且不再询问)
                    "Camera permission required for this feature to be available. " +
                            "Please grant the permission"
                }
                Text(textToShow)
                Button(onClick = {
                    //申请权限
                    cameraPermissionState.launchPermissionRequest()
                }) {
                    Text("Request permission")
                }
            }
        }
    }
}

accompanist-permissions
accompanist-permissions 详细使用

完结撒花~~~
徐某人不谈原理,只助你CV

等等!!!


2.jpg

你可能感兴趣的:(Compose 如何申请权限)