Skip to content

Instantly share code, notes, and snippets.

@mo0rti
Created May 19, 2023 10:23
Show Gist options
  • Save mo0rti/a45ecae6d2277805b7a586afff8452e5 to your computer and use it in GitHub Desktop.
Save mo0rti/a45ecae6d2277805b7a586afff8452e5 to your computer and use it in GitHub Desktop.
@Composable
fun LocationDisplay(activity: ComponentActivity) {
// Create a conflated channel for location updates
val locationChannel = remember { Channel<Location>(Channel.CONFLATED) }
// Create a mutable state for the location text
val locationState = remember { mutableStateOf("") }
// Receive location updates from the channel using a coroutine
LaunchedEffect(locationChannel) {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
locationChannel.receiveAsFlow().collect { location ->
locationState.value = "Lat: ${location.latitude}, Lng: ${location.longitude}"
}
}
// You also can use this code to get the location from the location channel.
/*
for (location in locationChannel) {
locationText.value = "Lat: ${location.latitude}, Lng: ${location.longitude}"
}
*/
}
// Request location updates from the phone's GPS hardware
DisposableEffect(activity) {
val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationListener = LocationListener { location ->
locationChannel.trySend(location)
log("Location updated")
}
requestLocationUpdatesIfNeeded(locationManager, locationListener)
onDispose {
locationManager.removeUpdates(locationListener)
}
}
Text("Location: ${locationState.value}")
}
// Request location updates if permissions are granted
@SuppressLint("MissingPermission")
private fun requestLocationUpdatesIfNeeded(locationManager: LocationManager, locationListener: LocationListener) {
if (hasPermissions()) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, locationListener)
}
}
val requiredPermissions = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
)
val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
when {
permissions.isEmpty() -> {}
permissions.containsValue(false) -> log("Permissions denied")
else -> log("Permissions granted")
}
}
// Check if required permissions are already granted
private fun hasPermissions() = requiredPermissions.all { (ActivityCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED) }
// Request required permissions if not already granted
private fun requestRequiredPermissions() {
if (!hasPermissions()) {
requestPermissionLauncher.launch(requiredPermissions)
return
}
log("Permission previously granted")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment