I have an application that listens for screen off, and user present intents. Since you cant register to receive screen off intents from the manifest, I am registering them in a service.
Do I really need to have a whole service to ensure that I always get notified of when the screen shuts off, and the user unlocks the phone? Seems really wasteful 🙁
The code I use in my service:
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service created.");
// register receiver that handles user unlock and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
Please consider what you are broadly trying to do, and a different way to do it.
Yes, the only way to monitor the events is to be actively registered. This is very intentional, because they are a very tempting thing for applications to think they want to be told about, and ending up with a bunch of apps having to be launched each time the user turns their screen on or off would end up with a really bad user experience.
Given that, I can tell you right now that there is no way you can guarantee that you will see these events, besides using a service that is always running and has used startForeground() to prevent itself from being killed. Obviously, this is not something you want to do unless your app is doing something the user very deliberately cares about having running for them when they decide it should be.
So… what are you trying to accomplish?