Android开发之BroadcastReceiver的使用

时间:2022-06-22 18:20:37

1.静态注册。

在manifest中注册。

 <receiver android:name="com.exce.learnbroadcastreceiver.MyReceiver"></receiver>

然后在activity中使用sendBroadcast(Intent)方法。其中参数是Intent.

 Intent intent=new Intent(this,MyReceiver.class);
intent.putExtra("data", "exer"); //携带数据
sendBroadcast(intent);

2.动态注册。

不需要在manifest中注册。

在代码中使用registerReceiver()和unregisterReceiver()进行广播的注册和取消注册。

registerReceiver(BroadcastReceiver receiver, IntentFilter filter),第一个参数是receiver,第二个参数是intentfilter。

unregisterReceiver(BroadcastReceiver receiver),参数是receiver。

代码:

 private MyReceiver receiver;
...
 case R.id.regBroadCast:
if (receiver==null) {
receiver=new MyReceiver();
registerReceiver(receiver, new IntentFilter(MyReceiver.ACTION));
}
break;
case R.id.unRegBroadCast:
if (receiver!=null) {
unregisterReceiver(receiver);
receiver=null;
}

MyReceiver:

 public static final String ACTION="com.exec.learnbroadcastreceiver.intent.action";

通过常量ACTION,new IntentFilter(MyReceiver.ACTION)获得intentFilter。然后就可以注册广播。

动态注册的广播,一定要在销毁的时候进行取消注册。即registerReceiver()和unregisterReceiver()必须同时出现。

3.Broadcast的优先级

BroadcastReceiver的优先级可以通过manifest中的intent-filter的android:priority=""属性。android:priority="9"需要填写一个数字,数字越大,优先级越高。

实现有序广播,可以使用sendOrderedBroadcast(Intent intent, String receiverPermission)方法,然后配合android:priority=""属性,进行有序广播

同时想要截断广播的话,在继承BroadcastReceiver的MyReceiver的onReceive()方法中使用abortBroadcast()方法,就可以截断广播。