i´m doing an application on jetpack compose and kotlin. it is an app to location an android device. i need to implement run time permissions to follow the jetpack filosofy. i have a menu page where there is a switch that when is activate saves the location of the device but just activate the switch it is necesary to request permissions "fine_location", "coarse_location" and "back_groundlocation". this is my menu.kt code:
LazyColumn {
item {
Row {
Box(
modifier =
Modifier.fillMaxWidth(0.8f)
)
{
Text(
color = Color.Black,
text = stringResource(R.string.location_gps),
fontSize = 30.sp,
modifier = Modifier.padding(20.dp)
)
}
Box(
modifier =
Modifier.fillMaxSize(),
contentAlignment = Alignment.CenterEnd
) {
Switch(
checked = checkedStateGps.value,
onCheckedChange = { checkedStateGps.value = it },
modifier = Modifier
.padding(20.dp),
colors= SwitchDefaults.colors(
//color of switches
checkedThumbColor = Color(0xFF00CC99),
checkedTrackColor = Color(0xFF7BB661),
uncheckedThumbColor = Color(0xFF83010B),
uncheckedTrackColor = Color(0xFFBB4C4C)
)
)
}
}
i´d want to know how can i implement acompanist permissions for this. thanks
CodePudding user response:
In Compose you can use Google's Accompanist library to request permission at runtime, just with PermissionRequired
.
This is an example with camera permission but you can request any permissions you have in your manifest file as android.Manifest.permission.*
var doNotShowRationale by rememberSaveable { mutableStateOf(false) }
val cameraPermissionState = rememberPermissionState(android.Manifest.permission.CAMERA)
PermissionRequired(
permissionState = cameraPermissionState,
permissionNotGrantedContent = {
if (doNotShowRationale) {
Text("Feature not available")
} else {
Column {
Text("The camera is important for this app. Please grant the permission.")
Spacer(modifier = Modifier.height(8.dp))
Row {
Button(onClick = { cameraPermissionState.launchPermissionRequest() }) {
Text("Ok!")
}
Spacer(Modifier.width(8.dp))
Button(onClick = { doNotShowRationale = true }) {
Text("Nope")
}
}
}
}
},
permissionNotAvailableContent = {
Column {
Text(
"Camera permission denied. See this FAQ with information about why we "
"need this permission. Please, grant us access on the Settings screen."
)
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = navigateToSettingsScreen) {
Text("Open Settings")
}
}
}
) {
Text("Camera permission Granted")
}