Android动态广播的注册与销毁

一个内部类:BroadcastReceiver的子类,并定义收到广播之后的操作:

1 class LockScreenBroadcastReceiver extends BroadcastReceiver{
2 
3         @Override
4         public void onReceive(Context context, Intent intent) {
5             //接收到广播之后的操作
6             KLog.d("收到广播");
7             LockScreenNightRestActivity.this.finish();
8         }
9     }

定义action和BroadcastReceiver子类对象:

1 //定义关闭此activity的action
2     public static final String NIGHT_REST_ACTIVITY_FINISH = "night_rest_activity_finish";
3     private LockScreenBroadcastReceiver broadcastReceiver;

 

onCreate中注册:

 1 @Override
 2     protected void onCreate(Bundle savedInstanceState) {
 3         super.onCreate(savedInstanceState);
 4 
 5         // 1. 实例化BroadcastReceiver的子类对象
 6         broadcastReceiver = new LockScreenBroadcastReceiver();
 7         IntentFilter intentFilter = new IntentFilter();
 8         // 2. 设置接收广播的类型
 9         intentFilter.addAction(NIGHT_REST_ACTIVITY_FINISH);// 只有持有相同的action的接受者才能接收此广播
10         // 3. 动态注册:调用Context的registerReceiver()方法
11         registerReceiver(broadcastReceiver, intentFilter);
12     }

onDestroy中注销:

1  //销毁onResume()中的广播
2         unregisterReceiver(broadcastReceiver);

 

posted on 2019-09-20 09:22  ken9527just  阅读(3337)  评论(0编辑  收藏  举报

导航