Android notification of screen off/on
I'm looking to see if there's a system notification I can list开发者_高级运维en for to see when the screen turns off/on. Any thoughts? Something similar to when the network connects/disconnects.
Easiest way is to put this in your MyApplication.onCreate()
method:
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d(TAG, Intent.ACTION_SCREEN_OFF);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d(TAG, Intent.ACTION_SCREEN_ON);
}
}
}, intentFilter);
The system will broadcast when the screen turns on and off -
In order to listen for these, you can create a BroadcastReceiver that listens for the events:
Intent.ACTION_SCREEN_OFF
Intent.ACTION_SCREEN_ON
They're listed in the documentation here:
Also, there's a tutorial about responding to these events that you might find useful.
For anyone looking for Kotlin equivalent code to the top answer , this worked for me:
val intentFilter = IntentFilter(Intent.ACTION_SCREEN_ON)
intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
registerReceiver(object: BroadcastReceiver() {
override fun onReceive(context:Context, intent:Intent) {
if (intent.action == Intent.ACTION_SCREEN_OFF) {
Log.d(TAG, Intent.ACTION_SCREEN_OFF)
}
else if (intent.action == Intent.ACTION_SCREEN_ON) {
Log.d(TAG, Intent.ACTION_SCREEN_ON)
}
}
}, intentFilter)
(the auto Kotlin conversion in Android Studio didn't work for me, so I quickly rewrote the snippet - hopefully it saves someone else that extra minute or two)
精彩评论