Android的四大组建之一--BroadcastReceiver

前面介绍了Service,接着介绍下相对简单的BroadcastReceiver;

Base class for code that will receive intents sent by sendBroadcast(). You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml. 

(大致的意思:BroadcastReceiver是用于接收通过sendBroadcast()发送的intents。可以通过Context.registerReceiver()动态注册一个实例,或者在AndroidManifest.xml中静态注册)

 

广播接收器只能用于接受广播,对广播的通知做出相应的处理,很多广播是由系统提供的(如电量不足等);

广播接收器同样没有界面,但是他们可以接受到信息后启动activity或者通过notificationManger通知用户(响铃,振动等);

 

广播分为两类:

Normal broadcasts:(通过sendBroadcast()发送),是异步的。全部的广播接收者运行时的顺序是不确定的,逻辑上可以在同一时刻所有接收者接收到,消息传递的效率比较高,但缺点是:接收者不能将处理结果传递给下一个接收者,并且无法终止广播Intent的传播;

Ordered broadcasts :(通过sendOrderBroadcast()发送),一次只发送给一个接收者,接受者都是有序,能够传递结果给下一个接收者,或者放弃广播(这样后面的广播接收者都收不到广播)。按照接收者声明的优先级别(声明在intent-filter元素的android:priority属性中,数越大优先级别越高(如果权限值想听则任意顺序),取值范围:-1000到1000。也可以调用IntentFilter对象的setPriority()进行设置),被接收者依次接收广播。如:A的级别高于B,B的级别高于C,那么,广播先传给A,再传给B,最后传给C。A得到广播后,可以往广播里存入数据,当广播传给B时,B可以从广播中得到A存入的数据。

There are two major classes of broadcasts that can be received:
•Normal broadcasts (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. This is more efficient, but means that receivers cannot use the result or abort APIs included here.
•Ordered broadcasts (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order.
注意:
如果在onResume()中注册了接收者,则必须在onPause()中注销;
不要在onSaveInstanceState中注销,因为这样将不会被调用。

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值