广播是典型的观察者模式,发送发不关心接收方是否收到,也不关心接收方如何处理,实现发送方和接收方的解耦。
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(),可以只接收一次该广播。