Broadcast
广播的分类
是否静态 | 是否有序 |
---|---|
静态 | 有序 |
动态 | 普通 |
各种广播特点
静态广播
特点
- 在配置文件中 定义
- 在app未启动时也可接收
在配置文件中定义
同配置Activity的结构相同,通过action与category来匹配
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.zhao.intentdemo.testbc"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
动态注册广播
特点
- 在代码中对接收器进行注册
- 在app退出前需要结束注册
动态注册
//注册
registerReceiver(receiver, filter);
//解除注册
unregisterReceiver(receiver);
无序广播(普通)
特点
- 所有广播会一起收到广播
- 广播不可以被截断同时也不可以对传输的数据进行修改
发送序广播
- 设置需要匹配的action 与 category
- 然后发送出去
Intent intent = new Intent("com.zhao.BroadcastDemo.MY_BROADCASTRECEIVER");
sendBroadcast(intent);
有序广播
特点
- 广播的传递方式是一个接一个的传递的
- 若被某个接收器截断 后续接收器将无法再获取
- 可以对传输的数据进行修改 然后再传递到下一个接收器
- 可以添加匹配权限(若无权限 将无法匹配成功)
- 为每个监听器设置优先级
发送有序广播
Intent intent = new Intent("com.zhao.BroadcastDemo.MY_BROADCASTRECEIVER");
//发送有序广播 第二参数为添加的权限
sendOrderedBroadcast(intent,null);
截断有序广播(后续广播无法接收)
public void onReceive(Context context, Intent intent) {
//截断 不继续传递广播
abortBroadcast();
}
设置接收器的优先级
<receiver android:name=".BroadcastReceiver_3" >
<intent-filter android:priority="10">
<action android:name="com.zhao.BroadcastDemo.MY_BROADCASTRECEIVER"/>
</intent-filter>
</receiver>
android:priority=”10” 值越大 优先级越高
修改广播中传输的数据(后续广播将收到经过该接收器处理过的数据)
public void onReceive(Context context, Intent intent) {
Bundle bundle = new Bundle();
bundle.putString("msg","new data");
//用自己定义的Bundle 替换数据
setResultExtras(bundle);
}