码迷,mamicode.com
首页 > 移动开发 > 详细

android Broadcast 总结

时间:2017-04-29 23:39:24      阅读:390      评论:0      收藏:0      [点我收藏+]

标签:cti   family   cal   好的   end   uri   err   round   font   



   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 会觉得该程序无响应。


















android Broadcast 总结

标签:cti   family   cal   好的   end   uri   err   round   font   

原文地址:http://www.cnblogs.com/zhchoutai/p/6786370.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!