sticky broadcast 是什么

sticky 类型的广播会保存 上次广播的intent,  只要你注册到这个广播, 就可以直接获得上次的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 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,则以后也得不到。

①在AndroidManifest.xml中注册

在配置文件中注册的接收者的特点是即使应用程序已被关闭,该接收者依然可接受它感兴趣的广播,比如手机电池电量的广播接收者,没有必要将某个程序开启。下面的例子1、2广播接收者会接收到拨打电话的广播。

②在Activity中注册

在Activity中绑定接收者必须依附该应用程序存在,或者一个BroadcastReceiver用于更新UI,就没有必要再程序关闭时接收者还运行,故无需在AndroidManifest.xml中注册而可以放在Activity中注册。
这个时候好像只有activity在resume状态时才能收到广播

广播接收者的生命周期只有10秒左右,如果需要大处理,要放到service里面, 最好不要用子线程, 如果用子线程,当广播消失时,子线程也有可能消失。

猜你喜欢

转载自sdkongkong.iteye.com/blog/1921206