Skip to content

Instantly share code, notes, and snippets.

@walteranyika
Last active June 12, 2025 08:13
Show Gist options
  • Save walteranyika/439ab5e235be677705d458c03ebc1054 to your computer and use it in GitHub Desktop.
Save walteranyika/439ab5e235be677705d458c03ebc1054 to your computer and use it in GitHub Desktop.
// implementation("com.google.android.gms:play-services-location:21.3.0")
@Composable
fun getPermissionsLauncher(context: Context): ManagedActivityResultLauncher<Array<String>, Map<String, Boolean>> {
val permissionLauncher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestMultiplePermissions())
{
val fineLocationGranted = it[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
val courseLocationGranted =
it[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false
if (fineLocationGranted || courseLocationGranted) {
//start fetching coordinates
Toast.makeText(context, "Permissions granted", Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(context, "Please grant location permission", Toast.LENGTH_SHORT)
.show()
}
}
return permissionLauncher
}
// Helper function to check permissions
fun hasLocationPermissions(context: Context): Boolean {
return ContextCompat.checkSelfPermission(
context, Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
context, Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
// Helper function to check if GPS is enabled
fun isGpsEnabled(context: Context): Boolean {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
)
}
// Helper function to fetch current location
@SuppressLint("MissingPermission") // Checked by calling function
fun fetchCurrentLocation(
context: Context,
fusedLocationClient: FusedLocationProviderClient,
onSuccess: (Double, Double) -> Unit,
onFailure: (String) -> Unit
) {
if (!isGpsEnabled(context)) {
onFailure("GPS is disabled.")
// Optionally prompt user to enable GPS here
context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
return
}
val cancellationTokenSource = CancellationTokenSource()
fusedLocationClient.getCurrentLocation(
Priority.PRIORITY_HIGH_ACCURACY, // Or PRIORITY_BALANCED_POWER_ACCURACY
cancellationTokenSource.token
).addOnSuccessListener { location ->
if (location != null) {
onSuccess(location.latitude, location.longitude)
} else {
onFailure("Unable to get current location (null).")
}
}.addOnFailureListener { exception ->
onFailure("Location fetch exception: ${exception.message}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment