Android - Broadcast Receivers
- Broadcast Receivers can be considered as both Application Components and Inter Process Communication (IPC) mechanisms
- As an IPC mechanism, Broadcast Receivers enable communication between different applications by sending and receiving Intents
- These Intents can be sent by the Android system, other apps, or the app itself
- As an Application Component, Broadcast Receivers are designed to respond to system-wide or custom events broadcasted by other applications
- Broadcast Receivers can act as a messaging system between different components across the Android ecosystem
- For example, the system broadcasts an event when the device starts charging
- Similarly, an app can send a custom broadcast to let other apps know that new data has been downloaded
- Broadcast Receivers extend the
BroadcastReceiver class and override the onReceive() method to match a specified Intent Filter declared in the AndroidManifest.xml - The following example shows a Broadcast Receiver handling an event where the device is charging.
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
switch (action) {
case Intent.ACTION_POWER_CONNECTED:
// Handle the power connected event
break;
case Intent.ACTION_POWER_DISCONNECTED:
// Handle the power disconnected event
break;
default:
// Handle other actions as needed
break;
}
}
}
}
<manifest ...>
<application ...>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
</manifest>
- The following methods are used for sending broadcasts to different kinds of receivers.
| Method | Description |
sendOrderedBroadcast(Intent, String) | Sends broadcasts to one receiver at a time. |
sendBroadcast(Intent) | Sends broadcasts to all receivers in an undefined order. |
localBroadcastManager.sendBroadcast(intent) | Send Intent broadcasts to local objects within your process .This method is deprecated since API 28, and LiveData is used instead.
|
- Similar to Android Activity, broadcasting messages through ADB is also possible
- Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers
- Manifest can not be used to declare receivers for most implicit broadcasts (broadcasts that don't target your app specifically)
- However, exceptions exist and can be found here.