监听屏幕亮灭状态

1. 注册监听

private BroadcastReceiver receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    final IntentFilter filter = new IntentFilter();
    // 屏幕灭屏广播
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    // 屏幕亮屏广播
    filter.addAction(Intent.ACTION_SCREEN_ON);
    // 屏幕解锁广播
    filter.addAction(Intent.ACTION_USER_PRESENT);
    // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
    // example:有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者“关机”对话框之上,
    // 所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
    filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                switch (action) {
                    case Intent.ACTION_SCREEN_ON:
                        LogUtils.i("screen on 屏幕点亮");
                        break;
                    case Intent.ACTION_SCREEN_OFF:
                        LogUtils.i("screen off 灭屏");
                        break;
                    case Intent.ACTION_USER_PRESENT:
                        LogUtils.i("screen unlock 解锁");
                        break;
                    case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
                        LogUtils.i("receive Intent.ACTION_CLOSE_SYSTEM_DIALOGS");
                        break;
                    default:
                        LogUtils.i("未知事件 " + action);
                        break;
                }
            }
        }
    };
    LogUtils.i("registerReceiver 注册屏幕监听成功");
    registerReceiver(receiver, filter);
}

2. 注销监听

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。