DEV Community

Haseeb
Haseeb

Posted on

Engineering Geofencing: Why My First Battery Drain Attempt Failed

The Silent Hum of Failure

It happened during a Friday prayer session, the one time you really, truly want silence. The imam had just begun the khutbah, the room was packed, and the atmosphere was thick with focus. Suddenly, from the pocket of the man sitting directly behind me, a loud, chirping notification sound cut through the silence like a knife. He fumbled, panicked, and eventually silenced it, but the distraction was absolute. I looked at my own phone, which I had manually silenced ten minutes earlier, and realized how much we rely on memory to manage these moments.

The Friction of Manual Management

We live in a world of constant notification, yet our devices remain surprisingly bad at understanding context. I found myself constantly toggling the mute switch before entering the mosque, then forgetting to turn it back on, leading to missed calls from my family later in the day. The problem isn't the hardware; the hardware is capable of everything. The problem is the user experience friction. Every manual switch is a task that relies on human fallibility. If you're stressed, running late, or simply distracted, you are going to mess up your sound profile.

Existing solutions usually rely on simple time-based schedules, which are fine until your meeting runs over or you arrive at the office early. I wanted something that reacted to where I was. I wanted a geofence. But as I started building Muffle, I quickly realized that geofencing on Android is not just about drawing a circle on a map. It’s a battlefield between accuracy and the OS’s aggressive battery optimization policies. If you poll the GPS too often, you kill the battery in three hours. If you poll it too infrequently, the user walks into the building, sits down, and their phone rings five minutes later. The gap between these two states is where the real engineering happens.

Solving the Geofencing Dilemma

My first attempt at building Muffle used a simple LocationListener inside a standard Service. I thought I could just set a high-frequency update interval and let the system handle the rest. I was wrong. Android’s Doze mode and App Standby buckets are designed to throttle exactly this type of behavior. My service was getting killed by the OS within minutes of the screen turning off. I needed to move to the GeofencingClient API, which offloads the heavy lifting to the Google Play Services location engine.

Using GeofencingClient was a significant architectural shift. Instead of managing the GPS hardware directly, I define GeofencingRequest objects with specific latitude, longitude, and radius parameters. The system then monitors these boundaries at the framework level, which is much more efficient than keeping an app process alive just to check coordinates. However, the trade-off is latency. When you enter a geofence, the system doesn't trigger the callback instantly; it waits for a confidence threshold to be met.

kotlin
val geofencingRequest = GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(geofenceList)
}.build()

geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent)
.addOnSuccessListener { /* Geofence added / }
.addOnFailureListener { /
Handle errors */ }

I struggled specifically with the INITIAL_TRIGGER_ENTER flag. If the user is already inside the radius when the app starts, the trigger doesn't always fire immediately. I had to implement a secondary check on app launch that compares the current Location against the stored Geofence coordinates using Location.distanceTo(). Without this manual verification step, the app would stay in a 'Normal' sound profile even when the user was physically standing inside their designated silent zone, rendering the entire automated system useless until the user left and re-entered the zone.

What Surprised Me: The Hardware Truth

What truly humbled me was discovering how inconsistent GPS hardware is across different manufacturers. I assumed that a location update would always contain the same level of accuracy metadata, but that’s not true. On some devices, the GPS chip reports a 'coarse' location that is wildly inaccurate, making a 50-meter geofence completely ineffective. I spent a week debugging why my triggers were firing while the user was still half a mile away, only to find that the system was falling back to network-based location because the GPS was struggling to get a fix inside a building.

If I were starting over, I wouldn't have relied so heavily on GPS alone. I would have implemented a hybrid approach that weights Wi-Fi BSSID signals alongside the GPS coordinates. It turns out that detecting a specific Wi-Fi network at a location is far more reliable and battery-efficient than keeping the radio active for a location fix. Furthermore, I learned that you cannot trust the onReceive callback to be timely. In my early versions, I tried to change the AudioManager settings directly within the broadcast receiver. This caused intermittent crashes when the system was under heavy memory pressure. I eventually moved the volume management logic into a dedicated WorkManager task, which ensures the operation completes even if the app process is momentarily reclaimed by the system.

Practical Takeaways for Android Devs

If you are building location-aware features, stop trying to fight the Android OS. Don't build your own background location polling loop; you will lose the battle against Doze mode every single time. Instead, embrace the platform’s intent-based APIs and focus your energy on handling the edge cases—like the initial entry logic I mentioned earlier. Always assume your location data will be stale or missing at the exact moment you need it most. Build your app to be resilient to these gaps by creating fallback mechanisms that check the state upon user interaction or app wake.

Automation is only useful if it is invisible and reliable. If the user has to open your app to fix a mistake the automation made, you’ve essentially just added more friction to their day. My goal with Muffle was to make sound management disappear from the user's list of daily chores. You can see how I approached these constraints and the final implementation at https://play.google.com/store/apps/details?id=com.muffle.app. Engineering for the physical world means accepting that your code will live in a volatile, resource-constrained environment, and that is where the real challenge lies.

Top comments (0)