Android唤醒屏幕并解锁

最近做一个类似闹钟的APP,需要定时唤醒屏幕并解锁,通过查找资料发现,有如下两种方式可以实现该功能

方式一:使用KeyguardManager.KeyguardLock和PowerManager.WakeLock实现

代码:

	KeyguardManager km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        //解锁
        kl.disableKeyguard();
        
        PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
        //获取锁
        wl.acquire();
        //释放锁
        wl.release();



需添加权限:



注意:加锁和解锁必须成对出现


方式二:使用android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 和android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON实现

代码:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

 
  
这句话必须在setContentView(R.layout.xxx)之前

FLAG_SHOW_WHEN_LOCKED:special flag to let windows be shown when the screen is locked. This will let application windows take precedence over key guard or any other lock screens. Can be used with FLAG_KEEP_SCREEN_ON to turn screen on and display windows directly before showing the key guard window. Can be used with FLAG_DISMISS_KEYGUARD to automatically fully dismisss non-secure keyguards. This flag only applies to the top-most full-screen window.

FLAG_KEEP_SCREEN_ON:as long as this window is visible to the user, keep the device's screen turned on and bright.

虽然两种方法都可以实现,但查看API文档发现如下

Android唤醒屏幕并解锁_第1张图片

所以还是建议使用方式二,不要申请上面的两个权限,也能达到相同的效果。

你可能感兴趣的:(Android)