广播接收器——BroadcastReceiver

什么是广播

广播是任何应用均可接收的消息。

什么是广播接收器

广播接收器本质上就是一个全局监听器,用于监听系统全局的广播消息,它可以非常方便的实现系统中不同组件之间的相互通信。

广播分类

  • 系统广播
  • 自定义广播

发送和接收广播

  • 发送:系统将针对系统事件(例如:系统启动或设备开始充电时)传递各种广播。通过将Intent传递给sendBroadcast()、sendOrderedBroadcast() 或 sendStickyBroadcast(),也可以将广播传递给其他应用。
  • 接收:广播接收器(Broadcast Receiver)

广播类型

  • 标准广播:是完全异步执行的广播,在广播发出后,所有的广播接收器几乎在同一时刻接收到这条广播,因此他们之间没有任何先后顺序可言。这种广播效率比较高,但是,这样的广播也是无法进行拦截的。
  • 有序广播:是一种同步执行的广播,在广播发出后,同一时刻只有一个广播接收器会接收到这条广播,当这个广播接收器中的逻辑执行完毕后,这条广播才会继续往下一个广播接收器传递。这样是有先后顺序的,优先级高的广播接收器会先接收到广播,并且前面的广播接收器可以拦截掉广播,这样,后面的广播接收器就无法接收到广播了。

广播接收器的注册方式

  • 动态注册:动态注册广播接收器可以自由的控制注册与注销,很灵活,缺点是必须要程序启动起来之后才能接收到广播,因为注册是写在onCreate()方法中的。
  • 静态注册:可以让程序在未启动的情况下就能接收到广播。

BroadcastReceiver 的生命周期

一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)的才有效的,当从该函数返回后,该对象就无效的了,结束生命周期。

Receiver Lifecycle(官方说明)

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

注意事项

  • 系统通过Intent激发BroadcastReceiver时,如果找不到合适的BroadcastReceiver组件,应用不会有任何问题。
  • 如果BroadcastReceiver的onReceive()方法不能在10秒中内执行完,系统就会认为该程序无响应。所以不能在onReceive()方法中执行耗时操作,否则会弹出ANR异常。
  • 如果确实需要根据BroadcastReceiver来完成一些比较耗时的操作,可以考虑通过Intent启动一个Service来完成该操作。不能使用新线程去完成耗时操作,因为BroadcastReceiver的生命周期很短,可能出现子线程还没结束,BroadcastReceiver就已经退出了的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值