Learning Resources

Broadcast Receivers of Android

A broadcast receiver is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file(or via code).

Alternatively to the this static registration, you can also register a BroadcastReceiver dynamically via the Context.registerReceiver() method.

This class will be able to receive intents. Intents can be generated via the Context.sendBroadcast() method.

The class BroadcastReceiver defines the onReceive() method. Only during this method your BroadcastReceiver object will be valid, afterwards the Android system can recycle the BroadcastReceiver. Therefore you cannot perform any asynchronous operation in the onReceive() method.

Sending Broadcast Intents
The sendBroadcast() method allows to send Broadcast Intents. You cannot trigger system Broadcasts, the Android system will prevent this.

But you can define intent-filters for your own actions and trigger them via the sendBroadcast() method.

The following AndroidManifest.xml file show a BroadcastReceiver which is registered to a custom action.

    android:versionName="1.0" >


        android:label="@string/app_name" >
            android:label="@string/app_name" >






You can trigger this event via the sendBroadcast() method.

Intent intent = new Intent();

Sticky Broadcast Intents
A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete.

You can can retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter) . This works also for a null BroadcastReceiver.

In all other ways, this behaves the same as sendBroadcast(Intent).

The Android system uses sticky broadcast for certain system information. For example the battery status is send as sticky Intent and can get received at any time. The following example demonstrates that.

// Register for the battery changed event
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

/ Intent is sticky so using null as receiver works fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null, filter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
    || status == BatteryManager.BATTERY_STATUS_FULL;

boolean isFull = 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;