DEV Community

Dy Labs
Dy Labs

Posted on

Building an Android app blocker without an AccessibilityService

Most Android app blockers rely on an AccessibilityService. It's the obvious tool: you get told whenever a window changes. It's also the reason some of them don't get along with the rest of your phone. Banking and other secure apps can refuse to run while an unknown accessibility service is enabled, and a blocker that breaks your bank app doesn't stay installed for long.

I removed it from my app, Recess, and went with polling instead.

Knowing which app is in front

UsageStatsManager gives you a stream of app events. Query a short recent window, take the latest resume event, and you know the foreground app. Keep the last value you saw, because during long continuous use of one app its event ages out of the window.

Polling once a second sounds wasteful, but it only happens while the screen is interactive. A receiver listens for screen on and off and starts or stops the loop, so an idle phone costs nothing.

Getting on top of another app

Starting an activity from the background is restricted from Android 10. The "display over other apps" permission grants an exemption, so the service can launch a full-screen activity over the blocked app.

My first version flickered. The poll fired while the block screen was still coming to the front, UsageStats still reported the blocked app, and the service launched another block screen. A flag for "block screen is showing" plus a short relaunch cooldown fixed it.

The foreground service type matters now

I shipped using the dataSync foreground service type. Android 15 then gave me two production crashes:

ForegroundServiceDidNotStopInTimeException, because dataSync services are limited to about 6 hours a day and mine runs all day.

ForegroundServiceStartNotAllowedException, because dataSync can't be started from BOOT_COMPLETED when targeting SDK 35 or higher.

The specialUse type fits this kind of service: no daily limit, and it's allowed at boot. It needs a manifest property describing the use, plus a declaration and a demo video in Play Console.

Two more safeguards are worth adding: implement onTimeout and stop promptly, and wrap every foreground start in a try/catch, because the OS can always refuse.

What polling can't fix

Battery Saver freezes the process and defers usage events, so blocking isn't reliable while it's on. All I can do is detect it and warn the user. OEM background killers remain the biggest headache.

If you've found a good way to survive OEM killers without accessibility, I'd love to hear it.

Recess is on Google Play: https://play.google.com/store/apps/details?id=com.recessapp.android

Top comments (0)