每当Android设备(运行Android 4.0以上)被锁定或解锁时,我都需要做一些事情。必要条件如下:
我已经实现了这段似乎适用于Android 5.0的代码,当"无"时,它会考虑the not-so-great behaviour of older Android versions。用来。在发布此问题之前,我还检查了其他问题,例如this one。
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
时是否有可能出现竞争条件。是否有可能除了"无"正在使用(例如" Swipe")并且当我处理ACTION_SCREEN_OFF
时,键盘锁不在限制输入模式中,但很快就会出现?如果是这种情况,我绝不会认为设备已锁定但可能是。