DEV Community

Haseeb
Haseeb

Posted on

Optimizing Android Geofencing: Lessons on Battery and Accuracy

It happened during a quiet Friday afternoon prayer. The masjid was silent, save for the soft murmur of the imam, when suddenly, a loud, upbeat ringtone tore through the solemn atmosphere. My pocket vibrated violently, the sound echoing against the high ceilings. I fumbled to silence it, feeling every single pair of eyes in the room turn toward me. It was a simple, preventable mistake: I had forgotten to flip the physical toggle on the side of my phone. That moment of visceral embarrassment stayed with me long after I left.

We have all lived through that friction. You step into a meeting, a lecture, or a library, and the mental overhead of remembering to silence your device is just one more task in an already busy day. Most people rely on their own memory, which is notoriously fallible. When you forget, the result is social friction—a notification pinging during a job interview or a phone call interrupting a professor. Existing solutions often feel like blunt instruments; they force you to set rigid time schedules that fail the moment your plans shift, or they require constant manual intervention that defeats the purpose of automation entirely.

I wanted to solve this by building Muffle. The goal was simple: my phone should know where I am and what sound state I need to be in, without me ever touching a setting once the rule was set. I decided to implement location-based triggers, or geofencing, to allow the device to act based on physical boundaries. However, as any Android developer knows, asking the OS to track location constantly is a recipe for battery disaster. The challenge wasn't just getting it to work; it was getting it to work without killing the user’s phone by noon.

When I first approached the GeofencingClient API, I assumed the default settings would be sufficient. I was wrong. The API requires a balance between responsiveness and power consumption. You define a circular region, a GeofencingRequest, and provide a transition type like GEOFENCE_TRANSITION_ENTER or GEOFENCE_TRANSITION_EXIT. If you set your responsiveness granularity too high, the system wakes up the GPS radio far too often. If you set it too low, you might walk deep into a building before the trigger finally fires. I spent weeks iterating on the LoiteringDelay and NotificationResponsiveness parameters to find a middle ground that felt instantaneous but stayed invisible to the battery monitor.

I eventually realized that combining GeofencingClient with FusedLocationProviderClient was necessary to maintain reliability. Relying solely on the geofence triggered by the system process sometimes led to misses if the device was in a deep sleep state. I implemented a BroadcastReceiver that handles the PendingIntent fired by the geofence, which then triggers a foreground service to update the AudioManager settings. Here is a simplified version of the logic I used to establish those boundaries:

kotlin
val geofence = Geofence.Builder()
.setRequestId("office_zone")
.setCircularRegion(lat, lng, 100f)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.setNotificationResponsiveness(1000 * 60) // 1 minute responsiveness
.build()

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

geofencingClient.addGeofences(request, pendingIntent)

This approach works because it offloads the heavy lifting to the OS's native geofencing service, which is highly optimized compared to a manual LocationListener implementation. By setting the NotificationResponsiveness to 60 seconds, I allowed the system to batch location checks, saving significant power while still ensuring the phone silenced itself well before any meeting actually began. The crucial part was managing the AudioManager.STREAM_RING state carefully so that manual user overrides could persist if they chose to unmute temporarily.

What truly surprised me during this development journey was how much the WifiManager state actually affects geofencing accuracy. I initially assumed that GPS was the only factor that mattered. I found that inside large urban buildings, the GPS signal is often unreliable due to multipath interference from glass and concrete. My geofences would sometimes trigger miles away because the OS relied on a bad tower lock. I eventually added a logic check that verifies signal accuracy before committing to a sound state change. If the Location object reports an accuracy radius greater than 150 meters, the app now waits for a more precise fix rather than blindly executing the routine.

I also learned that Do Not Disturb (DND) permissions are a minefield. Many users don't realize that modifying the NotificationManager requires a specific intent to be granted by the user in settings. Handling the edge case where a user revokes this permission while a routine is active was a headache. If I were starting over, I would build a much more robust error-handling wrapper around the NotificationManager calls from the very beginning. Instead of just trying to set the state, I would verify the permission status in every single BroadcastReceiver check to ensure the app doesn't crash silently when the user changes their system permissions.

Another lesson was the importance of the reboot lifecycle. My first build worked perfectly during a session, but as soon as the phone restarted, the geofences disappeared. I had to implement a BOOT_COMPLETED receiver to re-register all user routines. It seems obvious now, but when you are deep in the weeds of API documentation, it is easy to focus on the "happy path" and forget that Android is a volatile environment where processes are constantly killed and reborn. Managing that state persistence is what separates a toy app from a tool people actually trust.

For any developer working on background location or automation tasks, the biggest takeaway is to respect the system's battery optimizations. Do not fight the OS. If the OS wants to kill your background process to save power, let it. Design your logic so that your app can be cold-started by a system broadcast and pick up exactly where it left off. Use a local database like Room to store your routine state so that even if the app process is reclaimed by the system, the data remains intact. Never assume your service is always alive.

Also, spend time testing your location logic in real-world scenarios—not just while sitting at your desk. Walk through your building, go to a coffee shop, and drive through a tunnel. You will quickly find where your assumptions about constant connectivity fall apart. If you are building something that interacts with system volume or audio states, ensure you provide an "emergency bypass" or "priority contact" feature, as users are rightfully protective of their ability to be reached in actual emergencies. It is better to have an app that errs on the side of caution than one that silences a phone when it absolutely should be ringing.

Building tools that handle these small, annoying tasks is surprisingly rewarding. It forces you to think about how people actually use their devices rather than just how the code executes. Muffle has become my primary way of dealing with the noise of daily life. If you want to see how I’ve implemented these background services or just want a way to manage your own sound profiles without the manual hassle, you can check it out at https://play.google.com/store/apps/details?id=com.muffle.app. It is a work in progress, but it handles the job exactly how I needed it to.

Top comments (0)