Android BroadcastReceiver Basics


Example

BroadcastReceivers are used to receive broadcast Intents that are sent by the Android OS, other apps, or within the same app.

Each Intent is created with an Intent Filter, which requires a String action. Additional information can be configured in the Intent.

Likewise, BroadcastReceivers register to receive Intents with a particular Intent Filter. They can be registered programmatically:

mContext.registerReceiver(new BroadcastReceiver() {
    @Override
   public void onReceive(Context context, Intent intent) {
      //Your implementation goes here.
   }
}, new IntentFilter("Some Action"));

or in the AndroidManifest.xml file:

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="Some Action"/>
    </intent-filter>
</receiver>

To receive the Intent, set the Action to something documented by Android OS, by another app or API, or within your own application, using sendBroadcast:

mContext.sendBroadcast(new Intent("Some Action"));

Additionally, the Intent can contain information, such as Strings, primitives, and Parcelables, that can be viewed in onReceive.