Last active
May 23, 2023 19:07
-
-
Save oussama-dz/7603a3a867bd8e77c9376afc3d35b7d4 to your computer and use it in GitHub Desktop.
A composable function for requesting a single permission and multiple permissions.
This file contains hidden or 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
@Composable | |
fun Permissions() { | |
val activity = LocalContext.current as Activity | |
val permissionDialog = remember { | |
mutableStateListOf<NeededPermission>() | |
} | |
val microphonePermissionLauncher = rememberLauncherForActivityResult( | |
contract = ActivityResultContracts.RequestPermission(), | |
onResult = { isGranted -> | |
if (!isGranted) | |
permissionDialog.add(NeededPermission.RECORD_AUDIO) | |
} | |
) | |
val multiplePermissionLauncher = rememberLauncherForActivityResult( | |
contract = ActivityResultContracts.RequestMultiplePermissions(), | |
onResult = { permissions -> | |
permissions.entries.forEach { entry -> | |
if (!entry.value) | |
permissionDialog.add(getNeededPermission(entry.key)) | |
} | |
} | |
) | |
Column( | |
modifier = Modifier | |
.fillMaxSize(), | |
horizontalAlignment = Alignment.CenterHorizontally, | |
verticalArrangement = Arrangement.spacedBy( | |
16.dp, | |
Alignment.CenterVertically | |
) | |
) { | |
Button( | |
onClick = { | |
microphonePermissionLauncher.launch(NeededPermission.BLUETOOTH.permission) | |
} | |
) { | |
Text(text = "Request bluetooth Permission") | |
} | |
Button( | |
onClick = { | |
multiplePermissionLauncher.launch( | |
arrayOf( | |
NeededPermission.COARSE_LOCATION.permission, | |
NeededPermission.READ_CALENDAR.permission, | |
NeededPermission.READ_CONTACTS.permission | |
) | |
) | |
} | |
) { | |
Text(text = "Request multiple Permissions") | |
} | |
} | |
permissionDialog.forEach { permission -> | |
PermissionAlertDialog( | |
neededPermission = permission, | |
onDismiss = { permissionDialog.remove(permission) }, | |
onOkClick = { | |
permissionDialog.remove(permission) | |
multiplePermissionLauncher.launch(arrayOf(permission.permission)) | |
}, | |
onGoToAppSettingsClick = { | |
permissionDialog.remove(permission) | |
activity.goToAppSetting() | |
}, | |
isPermissionDeclined = !activity.shouldShowRequestPermissionRationale(permission.permission) | |
) | |
} | |
} | |
fun Activity.goToAppSetting() { | |
val i =Intent( | |
Settings.ACTION_APPLICATION_DETAILS_SETTINGS, | |
Uri.fromParts("package", packageName, null) | |
) | |
startActivity(i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment