Android监控屏幕解锁和点亮

来源:互联网 发布:独孤九贱php视频下载 编辑:程序博客网 时间:2024/05/01 00:38

   Android提供了广播,来监听屏幕解锁和屏幕点亮的事件,我们可以根据监听来进行我们自己想要的操作

步骤一:新建一个ScreenOnReceiver.java文件继承BroadcastReceiver

步骤二:重写public void onReceive(Context context, Intent intent)方法,在此方法里设置监听事件

@Override
    public void onReceive(Context context, Intent intent) {
        // 解锁
        if (intent != null && Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
            Toast.makeText(context, "屏幕已解锁", Toast.LENGTH_SHORT).show();   

         //可以在此添加自己想要在屏幕解锁后进行的操作
        }
    }

步骤三:监听屏幕点亮

// 判断屏幕是否点亮
    public boolean isScreenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm.isScreenOn( )) {
            return true;
        }
        return false;
    }


步骤四:在androidManifest.xml文件中注册广播(  </application>标签路径下)

</application>

..........

     <receiver android:name="【包路径】.ScreenOnReceiver" >
                 <intent-filter>
                      <action android:name="android.intent.action.USER_PRESENT" />
                 </intent-filter>
     </receiver>

...........

</application>

总结:

public class ScreenOnReceiver extends BroadcastReceiver {

    public ScreenOnReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // 解锁
        if (intent != null
                && Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
            // Toast.makeText(context, "屏幕已解锁", Toast.LENGTH_SHORT).show();
            if (isScreenOn(context)) {
                // 当屏幕点亮,进行自己的操作        
            }
        }
    }

    // 判断屏幕是否点亮
    public boolean isScreenOn(Context context) {
        PowerManager pm = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        if (pm.isScreenOn()) {
            return true;
        }
        return false;
    }
}


1 0
原创粉丝点击