stack-over-flow上面的一个解答,什么是sticky intent?
http://stackoverflow.com/questions/3490913/what-is-a-sticky-intent
官方的一个小例子:
http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
下面是官方引用:
http://developer.android.com/reference/android/content/Context.html#sendStickyBroadcast%28android.content.Intent%29
public abstract void sendStickyBroadcast (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 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.
Parameters
intent | The Intent to broadcast; all receivers matching this Intent will receive the broadcast, and the Intent will be held to be re-broadcast to future receivers. |
---|
See Also
sendBroadcast(Intent)
sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)
电池电量变化的guangbo
IntentFilter battery =
new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent currentBatteryCharge = registerReceiver(null, battery);
上面这个广播就是sticky intent,注册的时候,就已经取到最后一次发出的广播。可以从里面取数据。
可以看出,不是必须指定一个接收器去接收这个广播。
注意,要广播自己的sticky intent,程序必须配置BRAODCAST_STICK权限。
相关代码片段:
Start by determining the current charge status. The BatteryManager broadcasts all battery and charging details in a sticky Intent that includes the charging status.
Because it's a sticky intent, you don't need to register a BroadcastReceiver—by simply calling registerReceiver passing in null as the receiver as shown in the next snippet, the current battery status intent is returned. You could pass in an actual BroadcastReceiver object here, but we'll be handling updates in a later section so it's not necessary.
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
You can extract both the current charging status and, if the device is being charged, whether it's charging via USB or AC charger:
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Typically you should maximize the rate of your background updates in the case where the device is connected to an AC charger, reduce the rate if the charge is over USB, and lower it further if the battery is discharging.