Android Geofencing — Complete Guide
In this tutorial, you'll learn about Android Geofencing. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your geofence never triggers, or it triggers when the user is nowhere near the location (false positive).
Wrong Approach ❌
// Geofence with too small radius
val geofence = Geofence.Builder()
.setRequestId("store_1")
.setCircularRegion(lat, lng, 10f) // 10 meters — too small!
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build()
Output: Geofence rarely triggers due to GPS accuracy limitations.
Right Approach ✅
class GeofenceManager(private val context: Context) {
private val geofencingClient = LocationServices.getGeofencingClient(context)
fun addGeofence(lat: Double, lng: Double, radius: Float, id: String) {
// Minimum radius: 100m for reliable detection
val effectiveRadius = maxOf(radius, 100f)
val geofence = Geofence.Builder()
.setRequestId(id)
.setCircularRegion(lat, lng, effectiveRadius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_ENTER or
Geofence.GEOFENCE_TRANSITION_DWELL or
Geofence.GEOFENCE_TRANSITION_EXIT
)
.setLoiteringDelay(30000) // 30 seconds before DWELL triggers
.build()
val geofenceRequest = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(geofence)
.build()
val pendingIntent = getGeofencePendingIntent()
try {
geofencingClient.addGeofences(geofenceRequest, pendingIntent)
.addOnSuccessListener {
Log.d("Geofence", "Geofence added: $id")
}
.addOnFailureListener { e ->
Log.e("Geofence", "Failed to add geofence", e)
}
} catch (e: SecurityException) {
Log.e("Geofence", "Location permission not granted")
}
}
fun removeGeofence(id: String) {
geofencingClient.removeGeofences(listOf(id))
}
fun removeAllGeofences() {
geofencingClient.removeGeofences(getGeofencePendingIntent())
}
private fun getGeofencePendingIntent(): PendingIntent {
val intent = Intent(context, GeofenceBroadcastReceiver::class.java)
return PendingIntent.getBroadcast(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}
// BroadcastReceiver
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
GeofencingEvent.fromIntent(intent)?.let { event ->
if (event.hasError()) {
Log.e("Geofence", "Error: ${event.errorCode}")
return
}
val geofenceTransition = event.geofenceTransition
val triggeringIds = event.triggeringGeofences?.map { it.requestId }
when (geofenceTransition) {
Geofence.GEOFENCE_TRANSITION_ENTER -> {
Log.d("Geofence", "Entered: $triggeringIds")
}
Geofence.GEOFENCE_TRANSITION_DWELL -> {
Log.d("Geofence", "Dwelling: $triggeringIds")
}
Geofence.GEOFENCE_TRANSITION_EXIT -> {
Log.d("Geofence", "Exited: $triggeringIds")
}
}
}
}
}
Output: Reliable geofence detection with minimal false positives.
Prevention
- Use minimum 100m radius for reliable GPS-based detection.
- Use
DWELLtransition withloiteringDelayto confirm presence. - Request
ACCESS_BACKGROUND_LOCATIONfor geofencing in background. - Test in real-world conditions (GPS accuracy varies).
Common Mistakes with location geofence
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro