因为作一个项目,须要判断屏幕是否锁屏,发现网上方法不少,可是比较杂,如今进行总结一下:html
总共有两类方法:ide
1、代码直接断定spa
2、接收广播.net
如今先说第一类方法(代码直接断定):rest
一、经过PowerManager的isScreenOn方法,代码以下:code
1htm 2blog |
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 事件 boolean isScreenOn = pm.isScreenOn(); //若是为true,则表示屏幕“亮”了,不然屏幕“暗”了。 ci |
注释已经写的很明白了,如今大概说一下,
屏幕“亮”,表示有两种状态:a、未锁屏 b、目前正处于解锁状态 。这两种状态屏幕都是亮的
屏幕“暗”,表示目前屏幕是黑的 。
二、经过KeyguardManager的inKeyguardRestrictedInputMode方法,代码以下:
1 2 |
KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode(); |
注释已经写的很明白了,如今大概说一下,boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
源码的返回值的解释是:true if in keyguard restricted input mode.
通过试验,总结为:
若是flag为true,表示有两种状态:a、屏幕是黑的 b、目前正处于解锁状态 。
若是flag为false,表示目前未锁屏
注明:上面的两种方法,也能够经过反射机制来调用。
下面以第一个方法为例说明一下。
1 2 3 4 5 6 7 8 |
private static Method mReflectScreenState; try { mReflectScreenState = PowerManager. class .getMethod(isScreenOn, new Class[] {}); PowerManager pm = (PowerManager) context.getSystemService(Activity.POWER_SERVICE); boolean isScreenOn= (Boolean) mReflectScreenState.invoke(pm); } catch (Exception e) { e.printStackTrace() } |
如今介绍第二类方法(接收系统的广播):
接收系统广播事件,屏幕在三种状态(开屏、锁屏、解锁)之间变换的时候,系统都会发送广播,咱们只须要监听这些广播便可。
代码以下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
private ScreenBroadcastReceiver mScreenReceiver; private class ScreenBroadcastReceiver extends BroadcastReceiver { private String action = null ; @Override public void onReceive(Context context, Intent intent) { action = intent.getAction(); if (Intent.ACTION_SCREEN_ON.equals(action)) { // 开屏 } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 锁屏 } else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解锁 } } } private void startScreenBroadcastReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); context.registerReceiver(mScreenReceiver, filter); } |
做者: 一点点征服
出处:http://www.cnblogs.com/ldq2016/