Reputation: 3807
I want to be able to detect the phone lock event. When my app is running, if I press the red button (call end button/power button), the phone gets locked and the screen goes blank. I want to be able to detect this event, is it possible?
Upvotes: 25
Views: 33115
Reputation: 674
Koltin format of Robert's solution.
override fun onPause() {
super.onPause()
// If the screen is off then the device has been locked
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
val isScreenOn: Boolean = powerManager.isInteractive
if (!isScreenOn) {
// The screen has been locked
// do stuff...
}
}
I am assuming Kitkat version is quite old already.
Upvotes: 0
Reputation: 188
Register a broadcast with IntentFilter filter.addAction(Intent.ACTION_USER_PRESENT)
works pretty well even screen is turned on/off
Upvotes: 0
Reputation: 33545
Have a Broadcast Receiver
android.intent.action.SCREEN_ON
and
android.intent.action.SCREEN_OFF
Related: Read CommonsWare's Answer Here.
Upvotes: 18
Reputation: 38213
Alternatively you could do this:
@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...
}
}
Upvotes: 37