Sticky Broadcast(s) are a special kind of Broadcast(s) that remain active for awhile after being sent. You can send a sticky Broadcast with the method:
Context.sendStickyBroadcast()
If you register a BroadcastReceiver that listens to sticky Broadcast(s), it can receive two kind of Broadcast(s):
- Broadcast(s) that have just been sent
- Broadcast(s) that have been sent previously and are still active
You can find out what kind of Broadcast you have just received with the method:
isInitialStickyBroadcast()
returning false if the Broadcast represents an event that has just occured.Sticky Broadcast(s) are generally used for events lasting for a certain period of time. Examples of such Broadcast(s) sent by the system are:
- Intent.ACTION_BATTERY_CHANGED: indicates changes in the battery level. BroadcastReceiver(s) must be programmatically registered with Context.registerReceiver()
- Intent.ACTION_DOCK_EVENT: indicates when a device is placed on a dock
- Intent.ACTION_DEVICE_STORAGE_LOW: indicates low memory condition
public class MyBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_DOCK_EVENT)) {
if(!isInitialStickyBroadcast()) {
// this is a new broadcast
}
else {
// this is an old broadcast
}
}
}
}
In order to send sticky Broadcast(s) you must include the permission android.permission.BROADCAST_STICKY in the Manifest file.
If you want to remove a sticky Broadcast you can use the method:
Context.removeStickyBroadcast(Intent intent)
passing the Intent that was previously broadcast.
NB. Sticky Broadcast(s) consume system resources, so use them sparingly when really needed!
API level 21
Starting from API level 21 sticky Broadcast(s) are deprecated.
"Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired".




