##android屏幕解锁新解
最近因为一些事接触到android屏幕解锁这块,刚开始查询网上资料,绝大部分以keyguardLock 来进行获取屏幕锁和接触屏幕锁,其思路如下:
1 | KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE); |
然后在相应位置 释放持有的屏幕锁
但是这个思路有一个问题,在最后一次退出应用的时候由于释放的屏幕锁被系统回收,系统会再次锁屏,造成不好的用户体验,
经过翻阅api,发现有一个更好的解决方式:
在window对象中,存在这样一个flags :WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
位于 package android.view.WindowManager中。
其注释如下:
/** Window flag: when set the window will cause the keyguard to
* be dismissed, only if it is not a secure lock keyguard. Because such
* a keyguard is not needed for security, it will never re-appear if
* the user navigates to another window (in contrast to
* {@link #FLAG_SHOW_WHEN_LOCKED}, which will only temporarily
* hide both secure and non-secure keyguards but ensure they reappear
* when the user moves to another UI that doesn't hide them).
* If the keyguard is currently active and is secure (requires an
* unlock pattern) than the user will still need to confirm it before
* seeing this window, unless {@link #FLAG_SHOW_WHEN_LOCKED} has
* also been set.
*/
public static final int FLAG_DISMISS_KEYGUARD = 0x00400000;
其大意为:
窗口的标志: 当键盘锁不是安全的的时候(即基本的屏幕锁)设置该flags后该窗口显示会导致键盘锁被解锁。因为这种键盘锁不需要用于安全,如果用户导航到另一个窗口,它(键盘锁)将永远不会重新出现(相对于{@link #FLAG_SHOW_WHEN_LOCKED},这只是暂时隐藏安全和非安全的 keyguards,但r如果系统确保当用户移到另一个用户界面(即不在这个应用中),并不设置他们显示方式的时候,它们(键盘锁)又会出现(即键盘锁又恢复到了原来的正常状态而不是被获取释放等等))。如果键盘锁当前处于活动状态,并且是安全的 (比如手势屏幕解锁图案) 用户在看到自己的界面前仍然将需要进行解锁,除非用户还设置了 {@link #FLAG_SHOW_WHEN_LOCKED}。
So 用法如下 在你的oncreate()方法中,在你setContentView之前
你只需要为 window 添加相应flags:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.lockscreen);
即可大功告成!