欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

android Broadcast 总结

来源: 开发者 投稿于  被查看 7968 次 评论:212

android Broadcast 总结


 

 

1, 生命周期

在android官方文档中,推荐我们在onResume中进行 registerReceiver, 在onPause中进行unRegisterReceiver, 他们给出的理由是:

If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.

 

 

2,有序广播和无序广播的区别

广播接收者(BroadcastReceiver)用于监听系统事件或应用程序事件,通过调用Context.sendBroadcast()、Context.sendOrderedBroadcast()可以向系统发送广播意图,通过广播一个意图(Intent)可以被多个广播接收者所接收,从而可以在不用修改原始的应用程序的情况下,让你对事件作出反应。


其中Context.sendBroad()主要是用来广播无序事件(也被称为有序广播 Normal broadcast),即所有的接收者在理论上是同时接收到事件,同时执行的,对消息传递的效率而言这是比较好的做法。而Context.sendOrderedBroadcast()方法用来向系统广播有序事件(Ordered broadcast),接收者按照在Manifest.xml文件中设置的接收顺序依次接收Intent,顺序执行的,接收的优先级可以在系统配置文件中设置(声明在intent-filter元素的android:priority属性中,数值越大优先级别越高,其取值范围为-1000到1000。当然也可以在调用IntentFilter对象的setPriority()方法进行设置)。对于有序广播而言,前面的接收者可以对接收到得广播意图(Intent)进行处理,并将处理结果放置到广播意图中,然后传递给下一个接收者,当然前面的接收者有权终止广播的进一步传播。如果广播被前面的接收者终止后,后面的接收器就再也无法接收到广播了。

 

3, 持久广播 sendStickyBroadcast

sticky 类型的广播会保存 上次广播的intent, 只要你注册到这个广播, 就可以直接获得上次的intent 。(直到removeStickyBroadcast 该广播)

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 of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(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.

大概的意思是说: 发出的广播会一直滞留(等待),以便有人注册这则广播消息后能尽快的收到这条广播。其他功能与sendBroadcast相同。但是使用sendStickyBroadcast 发送广播需要获得BROADCAST_STICKY permission,如果没有这个permission则会抛出异常。

而有序类型的广播,则不会保存intent, 如果当时没得到intent,则以后也得不到。

 

 

4, 广播生命周期

每次广播到来时 , 会重新创建 BroadcastReceiver 对象 , 并且调用 onReceive() 方法 , 执行完以后 , 该对象即被销毁 . 当 onReceive() 方法在 10 秒内没有执行完毕, Android 会认为该程序无响应。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

用户评论