每当 Android 设备(运行 Android 4.0 及以上版本)被锁定或解锁时,我都需要做一些事情。要求如下:
- 如果屏幕锁定设置为“无”,我认为当按下电源按钮并且屏幕熄灭时设备不会被锁定。
- 如果屏幕锁定设置为“无”以外的任何值,我认为当键盘保护屏幕不存在时设备会被解锁。
我已经实现了这段似乎适用于 Android 5.0 的代码,并且考虑到了使用“无”时旧 Android 版本的不太好的行为。在发布此问题之前,我还检查了其他问题,例如这个问题。
private class KeyguardWatcher extends BroadcastReceiver {
public KeyguardWatcher() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_USER_PRESENT);
MyService.this.registerReceiver(this, intentFilter);
}
public void destroy() {
MyService.this.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
// Old Android versions will not send the ACTION_USER_PRESENT intent if
// 'None' is set as the screen lock setting under Security. Android 5.0
// will not do this either if the screen is turned on using the power
// button as soon as it is turned off. Therefore, some checking is needed
// with the KeyguardManager.
final String action = intent.getAction();
if (action == null) {
return;
}
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// If 'None' is set as the screen lock (ie. if keyguard is not
// visible once the screen goes off), we do not consider the
// device locked
if (mKeyguardManager.inKeyguardRestrictedInputMode()) {
doStuffForDeviceLocked();
}
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
if (!mKeyguardManager.inKeyguardRestrictedInputMode()) {
// The screen has just been turned on and there is no
// keyguard.
doStuffForDeviceUnlocked();
}
// If keyguard is on, we are to expect ACTION_USER_PRESENT when
// the device is unlocked.
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
doStuffForDeviceUnlocked();
}
}
}
这似乎在 Android 5.0 中对我有用。但是,我想知道是否有可能在处理时容易出现竞争条件ACTION_SCREEN_OFF
。是否有可能正在使用“无”以外的其他东西(例如“滑动”),并且在我处理ACTION_SCREEN_OFF
键盘保护时未处于受限输入模式,但很快就会出现?如果是这种情况,我永远不会认为设备被锁定,但它可能是。