[英]Android detect phone lock event
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?
我希望能够检测到这个事件,有可能吗?
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...
}
}
Register a broadcast with IntentFilter filter.addAction(Intent.ACTION_USER_PRESENT)
使用 IntentFilter 注册广播
filter.addAction(Intent.ACTION_USER_PRESENT)
works pretty well even screen is turned on/off即使屏幕打开/关闭也能很好地工作
Koltin format of Robert's solution.罗伯特解决方案的 Koltin 格式。
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.我假设 Kitkat 版本已经很旧了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.