I know it is the common problem and the common solution is to register the intent filter in manifest, not in the code. But the manifest registration doesn’t work for some actions, for example for android.intent.action.SCREEN_OFF and android.intent.action.SCREEN_ON.
How can I make sure that such receiver works exactly until it is unregistered by me in the code?
You can’t. Any component that registers a receiver can itself be destroyed due to inactivity/old age, to reclaim RAM for use by the rest of the OS. Plus, of course, the user can get rid of any component whenever the user wants via task killers and the Settings application.
The closest you can come is to use a service that also calls
startForeground()and putting aNotificationin the status bar. Again, the user can still get rid of it whenever desired. You would then have to convince the user that your application’s value is worth the cost of the everlasting service and the screen space for theNotification