DEV Community

Haseeb
Haseeb

Posted on

Building an Android Geofencing Engine without Draining Battery: A Technical Post-Mortem

It was the middle of a Friday congregational prayer. The mosque was silent, the imam was mid-recitation, and then it happened. Somewhere in the third row, a phone erupted with the default 'Radar' ringtone at maximum volume. The collective cringe was palpable. I felt the heat rise in my cheeks, even though it wasn't my phone. It was the third time that month I had witnessed someone’s device shatter the peace of a quiet space. I knew I needed a way to automate my own phone’s silence, but I was terrified of what that would do to my battery.

We have all been there. You walk into a meeting, a lecture, or a cinema, and you remember to silence your device exactly two seconds after the notification chime rings. Conversely, you leave that same place and forget to unmute, missing three important calls from your family or boss because your phone is still sitting in 'Do Not Disturb' mode. There are plenty of automation apps, but most are bloated, invasive, or rely on aggressive polling that keeps the CPU awake. I wanted something that felt like a native OS feature—invisible, lightweight, and strictly offline. I didn't want a background service that acted like a battery vampire, constantly pinging GPS satellites just to check if I was near my office or the local library.

The real challenge started when I decided to use the GeofencingClient provided by Google Play Services. The documentation suggests it is the gold standard, but the reality is more nuanced. If you simply define a radius and let the OS handle it, you are at the mercy of the device's location accuracy settings. I initially tried a coarse approach using PRIORITY_BALANCED_POWER_ACCURACY, but I found that in dense urban areas, the 'dwell' time—the period the phone takes to realize it has entered a geofence—was inconsistent. Sometimes it would trigger five blocks early, and sometimes I would already be inside the building before it registered the transition.

I shifted to a more granular approach. Instead of relying solely on the geofence transition intent, I implemented a local PendingIntent that wakes up the system only when the geofence boundary is crossed. To minimize battery drain, I avoid manual polling entirely. I use the addGeofences() method with GeofencingRequest.INITIAL_TRIGGER_ENTER to ensure the state is checked immediately upon registration. Here is the snippet of the core registration logic I settled on:

kotlin
val geofence = Geofence.Builder()
.setRequestId(routineId)
.setCircularRegion(lat, lon, radiusInMeters)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.build()

val request = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(geofence)
.build()

geofencingClient.addGeofences(request, geofencePendingIntent)

By keeping the GeofencingRequest minimal and offloading the heavy lifting to the Play Services location hardware abstraction layer, the app doesn't actually 'run' in the traditional sense while the screen is off. It registers the request with the OS, and the OS sends a broadcast to my BroadcastReceiver only when the hardware detects the crossing. This is the crucial distinction: the hardware is already tracking location for other system services; by piggybacking on that existing stream through GeofencingClient, I am not introducing a new, redundant high-power request. This prevents the 'wakelock' loops that plague poorly written background services.

What surprised me most during testing was how poorly the system handles overlapping geofences. My initial assumption was that the OS would treat them as independent entities. However, I discovered that if you have two small geofences that are near each other, the GEOFENCE_TRANSITION_EXIT for the first can sometimes be suppressed or delayed if the ENTER trigger for the second fires too quickly. This caused my phone to stay in 'Silent' mode even after I had left both locations. To fix this, I had to implement a custom 'Priority Resolver' in my backend logic. If a transition fires, I don't just change the sound profile; I query my local SQLite database to see if there are any other active routines that should currently be overriding the current state.

I also learned the hard way that 'airplane mode' is a developer's nightmare. When a user toggles airplane mode, the location services often reset or pause. If a user enters a geofence while in airplane mode and then leaves it, the exit event might never trigger because the radio hardware was powered down. I ended up adding a boot-complete receiver and a connectivity change listener that re-validates the current geofence status if the device uptime is high but the last transition timestamp is stale. It is a simple check, but it adds that extra layer of reliability that makes an app feel professional rather than buggy.

If I were starting over today, I would move away from relying on the GeofencingClient for everything. While it is efficient, it is a black box. If I had built a more robust fallback using FusedLocationProviderClient for periodic, low-frequency 'heartbeat' checks, I might have gained more control over edge cases where the OS kills the geofence service to save memory. Relying entirely on Google Play Services is convenient, but it means you don't always know why a transition failed. Adding a secondary, very infrequent location check as a 'sanity check' would have saved me weeks of debugging reports from users on older Android versions where power management is more aggressive.

For anyone looking to build location-aware features, my biggest piece of advice is to focus on the 'dwell' state rather than the 'transition' event. Everyone focuses on the moment the user crosses the line, but the reality of mobile usage is messy. You will get false positives. You will get gaps. Always design your system to be idempotent; if your app receives an 'ENTER' event twice, the volume should still be at the same level. If you can handle the state reactively based on your local database, you avoid the common pitfalls of state-sync issues. Think of your app as a state machine where the triggers are just inputs, rather than commands.

Building Muffle has been an exercise in restraint. The temptation to add more features—like predictive AI or social sharing—is constant, but the core value is in the silence. It is about removing the friction of human error in spaces where we need to be present. If you are interested in seeing how I handled the rest of the architecture—including the prayer time calculation engine and the priority system—you can find more details on how the app functions at https://play.google.com/store/apps/details?id=com.muffle.app. It is a locally-stored, privacy-first tool designed to help you regain focus by automating the one thing we all forget: turning the phone down.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The overlapping-geofence detail is the one that would have bitten me too — an EXIT getting suppressed because the ENTER of the next fence fired first is exactly the kind of race that's invisible until a user complains their phone stayed silent at home. Your instinct toward a low-frequency FusedLocationProviderClient heartbeat as a sanity check is the right one, but I'd make the interval adaptive rather than fixed: check more often when the device is moving toward a boundary and back off when it's stationary far from any fence, so the fallback itself doesn't become the battery drain you were avoiding. One thing I'd watch is how the heartbeat survives Doze and App Standby on Android 14+ — a periodic check that gets deferred by the OS can silently reintroduce the same stale-state problem. How are you resolving conflicts when two routines overlap — is there a priority stack, or does the most recently entered fence win?