惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
美团技术团队
博客园 - 司徒正美
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
大猫的无限游戏
大猫的无限游戏
罗磊的独立博客
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
J
Java Code Geeks
Last Week in AI
Last Week in AI
V
Visual Studio Blog
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
V
V2EX
C
Check Point Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Keeping Android Services Alive Against OEM Battery Aggres...
Haseeb · 2026-06-26 · via DEV Community

Haseeb

It was the middle of a Friday afternoon, and I was sitting in the front row of a local mosque. The room was deathly quiet, the kind of silence that amplifies every heartbeat. Suddenly, three rows behind me, a phone erupted with a loud, brassy ringtone that seemed to go on for an eternity. The man scrambled to silence it, his face turning bright red as he fumbled with his screen. I felt his humiliation deeply. In that moment, I realized that modern smartphones—despite their intelligence—are remarkably stupid when it comes to context-aware social etiquette.

We live in a world of smart devices, yet we are still manually toggling our volume settings like it is 2005. I have spent years forgetting to silence my phone before a meeting, a lecture, or a quiet space, only to have it buzz loudly at the worst possible time. It is a friction point that feels trivial until it happens to you, at which point it becomes incredibly disruptive. Existing solutions often fall into two camps: over-engineered automation tools that require a computer science degree to configure, or basic calendar-sync apps that lack the nuance needed for things like location-based triggers or recurring religious observances. I wanted something that just worked, quietly, in the background, without requiring me to constantly open an app to double-check if my rules were still active.

When I started building Muffle, I quickly realized that the greatest obstacle wasn't the logic of detecting a location or a prayer time—it was the operating system itself. Android, in its quest to squeeze every millisecond of battery life out of a device, has turned into a minefield for developers trying to keep background tasks alive. If you rely on a standard Service, the system will kill it within minutes as soon as the user turns the screen off. I needed a way to ensure that my background monitoring, especially for geofencing and prayer time calculations, stayed alive even when the phone was sitting in a pocket for hours.

I settled on using a Foreground Service coupled with a Notification that is impossible for the system to ignore easily. But that wasn't enough. Many OEMs, particularly those from manufacturers like Xiaomi, Oppo, and Samsung, implement aggressive custom battery management that kills processes despite standard Android documentation guidelines. I had to architect a system that didn't just rely on a single process. I implemented a JobScheduler as a secondary heartbeat. If the Foreground Service is terminated by a memory-hungry OEM process, the JobScheduler acts as a watchdog to restart the service.

kotlin
val serviceIntent = Intent(context, MuffleService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
// Using a JobScheduler to monitor the service status
val jobInfo = JobInfo.Builder(JOB_ID, componentName)
.setPeriodic(15 * 60 * 1000) // Every 15 minutes
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build()

This architecture ensures that even if the OS forces a closure, the app recovers quickly. However, the real secret sauce was not just in the code, but in the way I communicated with the user. I had to be transparent about why the notification was necessary. Users hate persistent notifications, but by explaining that this is the only way to ensure their phone stays silent during important events, the friction of seeing the icon turns into a sense of security. I treated the notification as a dashboard rather than an annoyance.

What truly surprised me during the development process was how much the AlarmManager behaves differently across API levels. I initially assumed that using setExactAndAllowWhileIdle would be enough to wake the device for a precise prayer time calculation. I was wrong. On newer Android versions, the system enforces a strict quota on how often an app can wake the device. If my app triggered too many alarms, the OS would actually throttle my app's ability to set future alarms, effectively silencing my app's internal clock. I spent three nights debugging why my triggers were missing, only to find a buried log entry indicating a BatteryManager restriction.

I also learned that GeofencingClient is far less reliable than I anticipated. In areas with poor GPS triangulation, the radius of a geofence can shift significantly, leading to false positives or, worse, failing to trigger entirely when a user walks into a building. If I were starting over, I would build a hybrid system that combines GeofencingClient with ActivityRecognitionClient. Instead of relying solely on coordinate proximity, I would monitor if the user has stopped moving for a specific duration after entering a boundary. This would eliminate the phantom triggers that happen when you simply drive past a location without actually stopping there. It is a classic case of "perfect on paper, messy in reality."

If you are building an app that requires background reliability, stop trusting the documentation that says standard services are sufficient. You have to assume the OS is actively trying to kill your app to save battery. This means your architecture must be modular. Your state must be saved to a local Room database before every single action, because you should assume your process will be wiped from memory at any second. If you don't have an onTaskRemoved implementation that gracefully handles cleanup and restart logic, you are going to see a flood of bug reports from users with specific device brands.

The most important lesson I learned is that transparency is a feature. When I decided to make Muffle a privacy-first, offline-only app, I was worried that users would miss out on cloud-synced settings. Instead, users appreciated that their location data never left their device. They were more willing to grant the "Battery Optimization" exceptions when they understood the data stayed local. If you provide a tangible benefit—like never having a phone ring in a lecture again—users are surprisingly forgiving of the overhead. You can find more about how I structured the persistence layer for Muffle at https://play.google.com/store/apps/details?id=com.muffle.app. Building for the real world means building for the edge cases that the documentation ignores.