DEV Community

Haseeb
Haseeb

Posted on

Maintaining Background State in Android Without Killing the Battery

It happened during a Friday prayer service. The mosque was silent, the kind of stillness that amplifies every minor movement. Then, my pocket exploded with a blaring notification chime. It wasn't just a ringtone; it was a loud, aggressive reminder that I had forgotten to silence my device again. I felt the collective gaze of a hundred people shift toward me. It was humiliating, and more importantly, it was entirely preventable. I realized then that my phone, despite being a 'smart' device, was failing at the most basic context-aware tasks.

We all have those moments. Whether it is a crucial boardroom meeting, a medical consultation, or a quiet library study session, the friction of manually toggling sound profiles is real. If you are like me, you don't just forget to silence the phone; you forget to turn the volume back up afterward, leading to missed calls from family or work. Existing solutions often felt bloated or required intrusive permissions that didn't align with my privacy concerns. I wanted a system that was local, offline-first, and smart enough to know where I was or what time it was without pinging a server every thirty seconds.

The challenge was clear: how do I build a background service that triggers sound profile changes based on location, calendar events, or prayer times without the Android OS killing it for battery optimization? In the current Android ecosystem, background execution is effectively a war of attrition between your app and the system's battery manager. I initially tried a standard Service that ran in the background, but the system would terminate it within hours. I then experimented with JobScheduler, but the latency was unacceptable for something like prayer times or geofencing, where you need a reaction within seconds of crossing a boundary.

I eventually settled on a combination of a Foreground Service with a persistent notification and WorkManager for non-critical tasks. The Foreground Service is necessary because it tells the Android system, 'Hey, the user knows this app is running, so please don't kill it.' However, keeping a service alive is only half the battle. The real issue is coordinating the triggers. I built a central RoutineManager that acts as the source of truth for the AudioManager state. For geofencing, I hooked into the GeofencingClient API, which is far more efficient than tracking location manually. By registering a PendingIntent, the OS handles the heavy lifting of waking up my app only when the device actually enters the defined circular radius.

kotlin
val geofencingRequest = GeofencingRequest.Builder().apply {
addGeofence(geofence)
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
}.build()

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

This approach avoids constant polling. The system tracks the location in the background, and my app remains dormant until the geofence transition fires. This is the only way to avoid the dreaded 'Battery Drain' report in the device settings. The AudioManager interaction is straightforward: I wrap calls to setRingerMode in a simple try-catch block to handle the NotificationManager.ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED permission requirement. Without this specific permission check, the app crashes immediately when trying to toggle Do Not Disturb mode on newer Android versions.

What surprised me most during this project was how fragile the AlarmManager can be for time-sensitive tasks. I initially assumed that setting an exact alarm for prayer times would be sufficient. I was wrong. On manufacturers like Xiaomi, Oppo, or Samsung, the 'Battery Optimization' settings are aggressive. Even with setExactAndAllowWhileIdle, my alarms were being delayed or silenced entirely. I had to implement a 'Reschedule' mechanism that checks the current time against the next expected trigger every time the phone boots. If the app detects that the system cleared the alarm, it re-registers the task immediately. You cannot trust the OS to maintain your schedule perfectly; your application must be defensive about its own state.

Another realization was the 'Priority' conflict. Initially, I thought simple chronological ordering would work. But what happens if a user has a 'Work' routine (silent) and a 'Meeting' routine (vibrate) that overlap? I had to implement a custom priority queue. Each routine is assigned a numerical weight. When a trigger fires, the RoutineManager compares the active routine's weight against the new one. If the new one is higher, it takes over. When that one ends, the system doesn't just go back to 'Normal'; it checks if the previous, lower-priority routine is still within its active time window. This recursive state checking was the single most complex part of the architecture. I spent three days debugging a scenario where the phone would stay silent forever because the 'restore' logic didn't account for overlapping time windows.

If I were to start over, I would lean much harder into the Room database for state persistence. I used shared preferences initially, but that became a nightmare as the complexity of the routine objects grew. Moving the entire state to a local SQL database allowed me to perform complex queries to find the 'next' active routine in milliseconds. It also made the activity log feature trivial to implement—I just query the history table by timestamp.

For any developer working on Android background services, the primary lesson is this: stop fighting the system. If you try to bypass battery optimization, the user will uninstall your app because their phone gets hot or the battery dies. Instead, use the specialized APIs provided by Google—WorkManager, GeofencingClient, and AlarmManager—and design your app to be 'stateless enough' to survive a process death at any moment. Your code should assume that it will be killed and restarted frequently. If you can handle an unexpected shutdown without losing track of the current sound profile, your app will be rock solid.

Building Muffle taught me that the most effective background tasks are the ones that do the least amount of work. I don't calculate prayer times every minute. I calculate them once for the day and store the timestamps. I don't track GPS constantly; I let the Google Play Services handle the geofence triggers and wake my app only when necessary. This is how you build a tool that feels like a native part of the operating system rather than a parasitic service. You can see how I approached the final implementation at https://play.google.com/store/apps/details?id=com.muffle.app, where I’ve focused on keeping the footprint small while ensuring the reliability required for daily use. Focus on the state, handle the reboots, and respect the hardware limitations.

Top comments (0)