Skip to content

Instantly share code, notes, and snippets.

@oussama-dz
Last active May 31, 2023 09:55
Show Gist options
  • Save oussama-dz/e725023299f6f54e06a34e25c82c54b6 to your computer and use it in GitHub Desktop.
Save oussama-dz/e725023299f6f54e06a34e25c82c54b6 to your computer and use it in GitHub Desktop.
A jetpack compose UI for testing the location service implementation.
@Composable
fun GetCurrentLocationUI() {
var currentLocation by remember {
mutableStateOf("")
}
val scope = rememberCoroutineScope()
val context = LocalContext.current
val permissionRequest = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestMultiplePermissions(),
onResult = { permissions ->
if (!permissions.values.all { it }) {
//handle permission denied
}
}
)
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp, Alignment.CenterVertically)
) {
Button(
onClick = {
scope.launch {
try {
val location = LocationService().getCurrentLocation(context)
currentLocation =
"Latitude: ${location.latitude}, Longitude: ${location.longitude}"
} catch (e: LocationService.LocationServiceException) {
when (e) {
is LocationService.LocationServiceException.LocationDisabledException -> {
//handle location disabled, show dialog or a snack-bar to enable location
}
is LocationService.LocationServiceException.MissingPermissionException -> {
permissionRequest.launch(
arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
)
}
is LocationService.LocationServiceException.NoNetworkEnabledException -> {
//handle no network enabled, show dialog or a snack-bar to enable network
}
is LocationService.LocationServiceException.UnknownException -> {
//handle unknown exception
}
}
}
}
}
) {
Text(text = "Get Current Location")
}
Text(text = currentLocation)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment