Created
March 2, 2022 16:48
-
-
Save Astroa7m/8be410b92a67f06a2af148b2f73b05b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@OptIn(ExperimentalPermissionsApi::class) | |
@Composable | |
fun PermissionRequest( | |
permission: String = Manifest.permission.CAMERA, | |
onPermissionPermanentlyDenied: @Composable () -> Unit, | |
onPermissionDenied: @Composable () -> Unit, | |
content: @Composable () -> Unit | |
) { | |
val permissionState = rememberPermissionState(permission) | |
val lifecycleOwner = LocalLifecycleOwner.current | |
DisposableEffect(key1 = lifecycleOwner) { | |
val observer = LifecycleEventObserver { _, event -> | |
if (event == Lifecycle.Event.ON_START) { | |
permissionState.launchPermissionRequest() | |
} | |
} | |
lifecycleOwner.lifecycle.addObserver(observer) | |
onDispose { | |
lifecycleOwner.lifecycle.removeObserver(observer) | |
} | |
} | |
when (permissionState.status) { | |
is PermissionStatus.Granted -> { | |
content() | |
} | |
is PermissionStatus.Denied -> { | |
if (permissionState.status.shouldShowRationale) { | |
onPermissionDenied() | |
} else { | |
onPermissionPermanentlyDenied() | |
} | |
} | |
} | |
} | |
@Composable | |
fun PermissionDeniedDialog(isPermanently: Boolean = false) { | |
var shouldShowDialog by remember { | |
mutableStateOf(true) | |
} | |
AnimatedVisibility(visible = shouldShowDialog) { | |
Dialog( | |
onDismissRequest = { shouldShowDialog = shouldShowDialog.not() } | |
) { | |
Column( | |
modifier = Modifier | |
.fillMaxWidth() | |
.padding(16.dp) | |
.background(MaterialTheme.colors.background) | |
.padding(16.dp), | |
verticalArrangement = Arrangement.SpaceEvenly, | |
horizontalAlignment = Alignment.End | |
) { | |
val title = | |
if (isPermanently) "Permission Denied Permanently" else "Permission is needed" | |
val description = | |
if (isPermanently) "Permission has been permanently denied to access scanner you should go to settings and enable it" | |
else "Permission is required in order to access camera features" | |
Text( | |
text = title, | |
fontSize = 20.sp, | |
fontWeight = FontWeight.Bold, | |
modifier = Modifier.fillMaxWidth(), | |
textAlign = TextAlign.Center, | |
color = MaterialTheme.colors.onBackground | |
) | |
Spacer(modifier = Modifier.height(8.dp)) | |
Text( | |
text = description, | |
modifier = Modifier.fillMaxWidth(), | |
textAlign = TextAlign.Center, | |
color = MaterialTheme.colors.onBackground | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment