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.…