android: broadcast receiver for screen on and screen off

The two actions for screen on and off are:

android.intent.action.SCREEN_OFF
android.intent.action.SCREEN_ON

But if you register a receiver for these broadcasts in a manifest, then the receiver will not receive these broadcasts.

For this problem, you have to create a long running service, which is registering a local broadcast receiver for these intents. If you do this way, then your app will look for screen off only when your service is running which won't irritate user.

PS: start the service in foreground to make it running longer.

A simple code snippet will be something like this:

IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);

Don't forget to unregister the receiver in the Service's onDestroy:

unregisterReceiver(mScreenStateReceiver);

Just in case for people who are asking why the receiver does not work with the declare broadcasts in manifest for ACTION_SCREEN_ON and ACTION_SCREEN_OFF:

https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_ON https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_OFF

You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

This is a protected intent that can only be sent by the system.