美文网首页Java面试题汇总
Android动态注册锁屏、解锁、开屏系统广播

Android动态注册锁屏、解锁、开屏系统广播

作者: 我最酷_b537 | 来源:发表于2019-11-27 10:40 被阅读0次

    先自定义一个广播类

    public class ScreenBroadcastReceiver extends BroadcastReceiver {
    
        private final static String TAG = "ScreenBroadcastReceiver";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "广播Action = " + action);
            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                Log.e(TAG, "锁屏");
                context.getApplicationContext().startService(new Intent(context.getApplicationContext(), RtmService.class));
            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
                Log.e(TAG, "解锁");
                context.getApplicationContext().startService(new Intent(context.getApplicationContext(), RtmService.class));
            } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
                Log.e(TAG, "开屏");
                context.getApplicationContext().startService(new Intent(context.getApplicationContext(), RtmService.class));
            }
        }
    }
    

    然后在Application中进行动态注册

        private ScreenBroadcastReceiver mScreenBroadcastReceiver;
    
    if (null == mScreenBroadcastReceiver)
                mScreenBroadcastReceiver = new ScreenBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_SCREEN_ON);  //解锁
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);  //锁屏
            intentFilter.addAction(Intent.ACTION_USER_PRESENT);  //开屏
            registerReceiver(mScreenBroadcastReceiver, intentFilter);
    

    因为是动态注册所以无需在AndroidManifest.xml中进行注册

    相关文章

      网友评论

        本文标题:Android动态注册锁屏、解锁、开屏系统广播

        本文链接:https://www.haomeiwen.com/subject/swzuwctx.html