Android Broadcast 特点分析

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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值