Created
January 27, 2022 12:14
-
-
Save manuelvicnt/f34f769b23b5b68ab81274db95cb7d15 to your computer and use it in GitHub Desktop.
Location permissions in Compose code
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
// In the Manifest file: | |
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> | |
// <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> | |
class RequestLocationPermissionsSample : ComponentActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
AccompanistSampleTheme { | |
Sample() | |
} | |
} | |
} | |
} | |
@OptIn(ExperimentalPermissionsApi::class) | |
@Composable | |
private fun Sample() { | |
val locationPermissionsState = rememberMultiplePermissionsState( | |
listOf( | |
android.Manifest.permission.ACCESS_COARSE_LOCATION, | |
android.Manifest.permission.ACCESS_FINE_LOCATION, | |
) | |
) | |
if (locationPermissionsState.allPermissionsGranted) { | |
Text("Thanks! I can access your exact location :D") | |
} else { | |
val allPermissionsRevoked = | |
locationPermissionsState.permissions.size == | |
locationPermissionsState.revokedPermissions.size | |
// If not all the permissions are revoked, it's because the user accepted the COARSE | |
// location permission, but not the FINE one. | |
if (!allPermissionsRevoked) { | |
Column { | |
Text( | |
text= "Yay! Thanks for letting me access your approximate location. " + | |
"But you know what would be great? If you allow me to know where you " + | |
"exactly are. Thank you!" | |
) | |
Spacer(modifier = Modifier.height(8.dp)) | |
Button(onClick = { locationPermissionsState.launchMultiplePermissionRequest() }) { | |
Text("Allow precise location") | |
} | |
} | |
} else { | |
// Both location permissions have been denied | |
if ( | |
locationPermissionsState.shouldShowRationale || | |
!locationPermissionsState.permissionRequested | |
) { | |
Column { | |
Text( | |
text= "Getting your exact location is important for this app. " + | |
"Please grant us fine location. Thank you :D" | |
) | |
Spacer(modifier = Modifier.height(8.dp)) | |
Button( | |
onClick = { locationPermissionsState.launchMultiplePermissionRequest() } | |
) { | |
Text("Request permission") | |
} | |
} | |
} else { | |
Text(text = "Ok so you don't want to give us permission... up to you!") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment