Android 广播

广播是典型的观察者模式,发送发不关心接收方是否收到,也不关心接收方如何处理,实现发送方和接收方的解耦。

Android广播分为,普通广播,有序广播,本地广播,和sticky广播

普通广播

普通广播,通过sendBroadcast()方法发送的广播,

优点:消息传递效率高。

缺点:1.所有接收器的执行顺序不一致,广播消息的处理结果不能发送给下一个接受者。

2.不能终止广播的传播,直到没有接受者为止。

使用步骤:

1.自定义继承自Broadcast的接收器,实现onreceive()

2.xml中注册,或者动态注册registerReceiver(),动态注册需要及时unregistere()

3.sendBroadcast(intent)。

有序广播

通过sendOrderedBroadcast()发送,广播按照优先级依次执行,优先级通过intent-filter的priority属性指定,值越大优先级越高,

通过setresult()将结果传递给下一个广播接受者,getresult()获得上一个接收器的处理结果,

可以使用abortBroadcast()终止广播。

本地广播

本地广播只是在进程内使用,v4包下的localBroadcastManager()实现应用内广播

使用api方法和普通广播类似,LocalBroadcastManager。getInstance(),registerReceiver(),unregisterReceiver(),sendBraodcastsync().

sticky 广播

sendStickyBroadcast()发送,发送后该广播会一直滞留,直到有接收器处理了该广播,并且只保留最后一个广播,当有广播接收器处理了该广播之后,再有符合的intent接收器依然会收到消息,官方解释:

Perform a sendBroadcast(Intent) that is “sticky,” meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value ofregisterReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same assendBroadcast(Intent).

You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission,SecurityException will be thrown.

使用removeRegisterReciver(),可以只接收一次该广播。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值