DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Location and Geofencing in Android Compose - FusedLocationProvider Complete Guide

Location services and geofencing enable location-aware Android applications. Discover how to integrate FusedLocationProvider and build geofence-based triggers using modern Kotlin patterns.

Getting Device Location with FusedLocationProvider

Use FusedLocationProviderClient to request location updates efficiently:

val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)

val locationRequest = LocationRequest.Builder(
    Priority.PRIORITY_HIGH_ACCURACY,
    1000  // Update interval in ms
).apply {
    setMinUpdateDistanceMeters(100f)
}.build()

val locationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult) {
        for (location in locationResult.locations) {
            Log.d("Location", "Lat: ${location.latitude}, Lon: ${location.longitude}")
        }
    }
}

fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
Enter fullscreen mode Exit fullscreen mode

Geofencing with GeofenceManager

Create geofences to trigger actions when users enter/exit boundaries:

val geofenceList = listOf(
    Geofence.Builder()
        .setRequestId("home")
        .setCircularRegion(40.7128, -74.0060, 100f)  // NYC, 100m radius
        .setExpirationDuration(Geofence.NEVER_EXPIRE)
        .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
        .build()
)

val geofencingRequest = GeofencingRequest.Builder()
    .addGeofences(geofenceList)
    .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
    .build()

geofencingClient.addGeofences(geofencingRequest, createPendingIntent())
Enter fullscreen mode Exit fullscreen mode

Integration with Flow and Coroutines

Combine location updates with Kotlin Flow for reactive programming:

fun observeLocationUpdates(): Flow<Location> = callbackFlow {
    val callback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult) {
            result.lastLocation?.let { send(it) }
        }
    }
    fusedLocationClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper())
    awaitClose { fusedLocationClient.removeLocationUpdates(callback) }
}
Enter fullscreen mode Exit fullscreen mode

Location-based features enhance user engagement. Always request appropriate permissions and test on actual devices for accuracy.

8 Android app templates on Gumroad

Top comments (0)