A Broadcast Receiver in Android is a component that allows an app to listen for and respond to global broadcast messages sent by the system or other apps. These broadcasts can notify the app of events, such as when the device is charging, when the Wi-Fi status changes, when an SMS is received, or when a new app is installed.
Key Points About Broadcast Receivers:
- Purpose:
- Broadcast Receivers allow your app to react to system-wide events or inter-app communications. For example, your app might listen for notifications when the device’s battery is low or when the user receives a text message.
- How Broadcast Receivers Work:
- Broadcasts: A broadcast is a message sent by the system or an app to notify all interested components that something has occurred. These can be either normal broadcasts (dispatched to all registered receivers) or ordered broadcasts (which are sent to one receiver at a time, allowing the receivers to modify or abort the broadcast).
- Receivers: The Broadcast Receiver listens for specific broadcast messages and performs actions when they are received.
- Types of Broadcast Receivers:
- System Broadcasts: These are broadcasted by the Android system, for example, “battery low,” “airplane mode changed,” “Wi-Fi connected,” etc.
- Custom Broadcasts: These are user-defined broadcasts that can be sent by an app to notify other components of the same or other apps.
- Lifecycle of a Broadcast Receiver:
- The lifecycle of a Broadcast Receiver is quite simple. It is triggered by the system when a relevant broadcast occurs. The receiver is active only for the duration of its
onReceive()
method. After this method completes, the receiver is destroyed.
- The lifecycle of a Broadcast Receiver is quite simple. It is triggered by the system when a relevant broadcast occurs. The receiver is active only for the duration of its
- Registered Broadcast Receivers:
- There are two ways to register a Broadcast Receiver:
- Static Registration: In the app’s manifest file, specifying which broadcasts your app is interested in. This allows the receiver to listen for broadcasts even when the app is not running.
- Dynamic Registration: Registering the receiver programmatically in the app code using the
registerReceiver()
method. This is useful when you want the receiver to only be active when a certain component (e.g., an Activity) is running.
- There are two ways to register a Broadcast Receiver:
Example of a Simple Broadcast Receiver:
1. Creating a BroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Handle the broadcast here
String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_LOW)) {
// Perform actions when the battery is low
Log.d("MyBroadcastReceiver", "Battery is low!");
}
}
}
2. Registering the Receiver in the Manifest (Static Registration):
To listen for system-wide broadcasts like battery low, you register the receiver in the app’s AndroidManifest.xml
:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW"/>
</intent-filter>
</receiver>
With this registration, your app will automatically listen for the battery low broadcast even when the app is not running.
3. Dynamic Registration (Registering in Code):
You can also register a BroadcastReceiver dynamically at runtime, for example, within an Activity:
public class MainActivity extends AppCompatActivity {
private MyBroadcastReceiver myReceiver;
@Override
protected void onStart() {
super.onStart();
myReceiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_LOW);
registerReceiver(myReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(myReceiver); // Unregister when no longer needed
}
}
In this case, the receiver listens for the battery low event only while the MainActivity
is running.
Sending a Custom Broadcast:
You can send a custom broadcast using sendBroadcast()
:
Intent intent = new Intent("com.example.MY_CUSTOM_BROADCAST");
intent.putExtra("message", "Hello, this is a custom broadcast!");
sendBroadcast(intent);
Other apps or components can listen for this broadcast by registering for the specific action "com.example.MY_CUSTOM_BROADCAST"
.
Important Considerations:
- Security: Be mindful of broadcasting sensitive data. If necessary, use LocalBroadcastReceiver to communicate only within your app.
- Performance: Avoid performing long-running tasks inside the
onReceive()
method of a BroadcastReceiver. If the task is lengthy, consider using a Service or AsyncTask to handle it in the background. - App States: Be cautious when your app receives broadcasts while in the background. For instance, it can be challenging to interact with UI components from within a BroadcastReceiver.
Common System Broadcasts:
- Intent.ACTION_BATTERY_LOW: Sent when the battery level is low.
- Intent.ACTION_POWER_CONNECTED: Sent when the device is plugged into power.
- Intent.ACTION_AIRPLANE_MODE_CHANGED: Sent when the airplane mode is turned on or off.
- Intent.ACTION_BOOT_COMPLETED: Sent when the device finishes booting.
- Intent.ACTION_Wifi_STATE_CHANGED: Sent when the Wi-Fi state changes.
Conclusion:
A Broadcast Receiver is an essential Android component for responding to system-wide or custom events. By implementing BroadcastReceivers, apps can stay aware of changes in device state and react accordingly. These receivers can be registered either statically (through the manifest) or dynamically (in code), allowing for flexible handling of different broadcast events.