DEV Community

Haseeb
Haseeb

Posted on

Architecting a Low-Power GPS Geofencing Engine for Android

It was the middle of a Friday afternoon prayer. The mosque was silent, the air heavy with focus, when suddenly, a high-pitched ringtone cut through the quiet like a knife. It was my phone. In that split second, I didn't just feel embarrassed; I felt like a failure as a developer. I had built complex systems for other companies, yet I couldn't solve the simple problem of my own device ringing at the worst possible time. I walked out, phone burning in my pocket, determined to never let that happen again.

We all have these moments. A board meeting, a medical consultation, or a quiet library study session where the sudden blare of a notification or a call ruins the environment. Manually toggling sound settings is a reactive process, and humans are notoriously bad at remembering to switch their phones back to 'normal' afterward. I’ve missed important calls for hours because I forgot to unmute my device after a meeting. Existing solutions often felt bloated, required constant internet connections, or simply weren't reliable enough to trust with my professional reputation.

I wanted a solution that was set-and-forget. I didn't want to rely on cloud services that could fail or privacy-invasive tracking. I needed something that understood context—time, location, and calendar events—to handle my sound profile automatically. But the real challenge wasn't just building the trigger logic; it was doing so without turning the user's phone into a paperweight by noon. Battery life is the ultimate constraint for any background-running Android utility, and I knew that if my app drained power, it would be uninstalled within twenty-four hours.

When I sat down to architect the location-based triggering for Muffle, the temptation was to use LocationManager and poll for coordinates periodically. That is the quickest way to destroy a battery. Instead, I turned to the GeofencingClient within the Google Play Services library. The beauty of this API is that it offloads the heavy lifting to the system’s location services, which aggregate data from GPS, Wi-Fi, and cellular towers to determine proximity to a defined radius without keeping the GPS hardware active in a high-accuracy state constantly.

However, even with the GeofencingClient, you have to be careful about your transition types. I initially set up listeners for both 'enter' and 'dwell' transitions, but I found that 'dwell' triggers are notoriously noisy in urban environments where GPS signals bounce off buildings. By sticking strictly to 'enter' and 'exit' transitions, I drastically reduced the number of unnecessary wake-locks. The implementation relies on a PendingIntent that wakes up a specific BroadcastReceiver only when the hardware-level fence is crossed. This is the code I landed on for adding a geofence:

kotlin
val geofence = Geofence.Builder()
.setRequestId(id)
.setCircularRegion(lat, lng, radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.build()

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

geofencingClient.addGeofences(geofencingRequest, pendingIntent)

This approach ensures the app remains dormant until the system detects the boundary crossing. The system handles the low-power monitoring, and my app only executes its logic when the transition actually occurs. By coupling this with an AlarmManager for time-based routines and a CalendarContract observer for scheduled events, I created a multi-layered trigger system that avoids the 'always-on' trap. The priority system I implemented on top of this ensures that if a user has two overlapping rules—say, a work location and a meeting time—the app doesn't fight itself. The logic simply evaluates the 'active' state of all routines and applies the sound profile associated with the highest priority rule.

What truly surprised me during development was how much the operating system interferes with background processes in the name of battery optimization. I spent weeks chasing a bug where geofences would simply stop firing after a reboot. I assumed it was a logic error in my database refresh, but it turned out that Android’s 'Doze' mode and manufacturer-specific battery restrictions were killing my background service because I hadn't explicitly handled the ACTION_BOOT_COMPLETED broadcast correctly. I had to register a Receiver that explicitly re-adds all active geofences to the GeofencingClient the moment the device finishes its boot sequence.

If I were starting over, I would move away from relying on the ForegroundService for the primary notification bar icon. While it keeps the app alive, it’s visually intrusive. I spent a long time trying to figure out how to satisfy the 'sticky notification' requirement while keeping it minimal, and I eventually realized that transparency about why the app is running is more important to the user than hiding the service. Users are surprisingly tolerant of a background app if you clearly explain in the UI that it's only consuming power to check geofence boundaries occasionally. I also underestimated the impact of Wi-Fi-based location estimation; in some rural areas, the geofences were too large because the system had to rely on distant cell towers rather than local Wi-Fi nodes. If I could redo the mapping, I would build a calibration tool into the app that lets users refine their boundary based on real-world testing rather than just a map pin.

For any developer working on background location or persistent tasks, the biggest takeaway is to respect the system's own throttling mechanisms rather than trying to bypass them. If you try to force your app to stay awake with a constant wake-lock, the OS will eventually flag your app as a battery drainer and stop it regardless of your code quality. Instead, leverage the APIs the OS provides for these tasks. Use WorkManager for tasks that don't need immediate execution, and use the system-level geofencing hardware for location. These APIs exist precisely because Google has spent years optimizing them to work across thousands of different device models and battery configurations.

Think about how your app interacts with the device’s lifecycle. Does it need to be awake at 3 AM? Probably not. Can your data be cached locally instead of fetched from a server every time a routine triggers? Definitely. Building for efficiency isn't just about saving battery; it’s about making your app a 'good citizen' on the device, which leads to higher retention and better user trust. I built Muffle because I wanted to solve the friction of constant manual sound management without compromising my phone’s performance. If you are struggling with similar issues, you can see how I approached the final product at https://play.google.com/store/apps/details?id=com.muffle.app, where I’ve kept the entire system offline and privacy-focused, ensuring that your location data never leaves your device.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The reboot detail is the one most people learn the hard way — the fence silently disappearing after a restart is exactly the kind of bug users report as "the app just stopped working" with no crash to chase. Two things I'm curious about: did Doze or the background-location permission ever delay your BOOT_COMPLETED re-registration in practice, and how do you handle a fence created while the user is already inside it — does INITIAL_TRIGGER_ENTER fire right away, or only on the next crossing? Dropping DWELL in favour of ENTER/EXIT only is a clean call too; most apps never need the dwell signal enough to pay for it.