Android判断屏幕锁屏的方法总结

来源:互联网 发布:三a甲级数据分析事务所 编辑:程序博客网 时间:2024/05/21 11:05

由于做一个项目,需要判断屏幕是否锁屏,发现网上方法很多,但是比较杂,现在进行总结一下:

总共有两类方法:

一、代码直接判定

二、接收广播

 

现在先说第一类方法(代码直接判定):

1、通过PowerManager的isScreenOn方法,代码如下:

 

?
1
2
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
booleanisScreenOn = pm.isScreenOn();//如果为true,则表示屏幕“亮”了,否则屏幕“暗”了。

注释已经写的很明白了,现在大概说一下,

 

屏幕“亮”,表示有两种状态:a、未锁屏 b、目前正处于解锁状态 。这两种状态屏幕都是亮的

屏幕“暗”,表示目前屏幕是黑的 。

 

2、通过KeyguardManager的inKeyguardRestrictedInputMode方法,代码如下:

 

?
1
2
KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
booleanflag = 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
privatestatic Method mReflectScreenState;
try{
    mReflectScreenState = PowerManager.class.getMethod(isScreenOn,newClass[] {});
    PowerManager pm = (PowerManager) context.getSystemService(Activity.POWER_SERVICE);
    booleanisScreenOn= (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
privateScreenBroadcastReceiver mScreenReceiver;
privateclass ScreenBroadcastReceiver extendsBroadcastReceiver {
    privateString action = null;
 
 
    @Override
    publicvoid onReceive(Context context, Intent intent) {
        action = intent.getAction();
        if(Intent.ACTION_SCREEN_ON.equals(action)) {          
            // 开屏
        }elseif (Intent.ACTION_SCREEN_OFF.equals(action)) {
            // 锁屏
        }elseif (Intent.ACTION_USER_PRESENT.equals(action)) {
            // 解锁
        }
    }
}
privatevoid startScreenBroadcastReceiver() {
    IntentFilter filter = newIntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    context.registerReceiver(mScreenReceiver, filter);
}

好了,就写这么多了,希望对大家有用!!
2 0
原创粉丝点击