<application> <receiver android:name=".MyBroadcastReceiver" android:enabled="true"> <intent-filter> <action android:name="android.intent.action.ACTION_SCREEN_ON"></action> <action android:name="android.intent.action.ACTION_SCREEN_OFF"></action> </intent-filter> </receiver> ... </application>
MyBroadcastReceiver
is set just to spit foo to the logs. Does nothing. Any suggestions please? Do I need to assign any permissions to catch the intent?
To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
Broadcast Receivers are used to listen for Broadcast Intents.
Broadcast intents are a mechanism by which an intent can be issued for consumption by multiple components on an Android system. Broadcasts are detected by registering a Broadcast Receiver which, in turn, is configured to listen for intents that match particular action strings.
A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.
I believe that those actions can only be received by receivers registered in Java code (via registerReceiver()
) rather than through receivers registered in the manifest.
Alternatively you can use the power manager to detect screen locking.
@Override protected void onPause() { super.onPause(); // If the screen is off then the device has been locked PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); boolean isScreenOn; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { isScreenOn = powerManager.isInteractive(); } else { isScreenOn = powerManager.isScreenOn(); } if (!isScreenOn) { // The screen has been locked // do stuff... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With