In Android development, a BroadcastReceiver is a component that allows your application to listen for and respond to broadcast messages from other applications or from the system itself. These messages can be about various events like changes in network connectivity, charging status, or custom events sent by other apps. BroadcastReceivers enable apps to react to changes in the system or in other apps without the need for a persistent service or constant polling.
What is a BroadcastReceiver?
A BroadcastReceiver in Android is used to listen for specific broadcast messages and act upon them. These broadcasts can either be sent by the system (e.g., when the device's battery is low or Wi-Fi is connected) or by other apps. Once a broadcast is received, the BroadcastReceiver can respond by executing some code or performing a specific action.
For example, an app might register a BroadcastReceiver to listen for an event such as:
- When the device connects to the internet.
- When the device’s battery level is low.
- When an SMS is received.
- When the screen is turned off or on.
How Does BroadcastReceiver Work?
-
Broadcast Sending: A broadcast is sent by a system service or another app. These broadcasts can be either:
- Normal Broadcasts: Sent asynchronously, allowing multiple receivers to receive the broadcast at the same time.
- Ordered Broadcasts: Sent in a specific order, allowing one receiver to handle the broadcast before others.
-
Broadcast Receiving: A BroadcastReceiver listens for specific broadcast messages. When a relevant broadcast is sent, the receiver will invoke a specific method (e.g.,
onReceive()) to process the broadcast. -
Unregistering: Once the receiver has processed the broadcast, you can unregister it to prevent it from listening to further broadcasts if necessary. If the receiver is registered in the manifest, it remains active until the app is uninstalled or the phone is restarted.
Types of Broadcasts in Android
-
System Broadcasts: These are sent by the system for general device events. Some common system broadcasts include:
android.intent.action.BOOT_COMPLETED: Sent when the device finishes booting.android.intent.action.BATTERY_LOW: Sent when the device's battery is low.android.net.conn.CONNECTIVITY_CHANGE: Sent when the network connection is established or lost.android.intent.action.AIRPLANE_MODE: Sent when airplane mode is toggled.
-
Custom Broadcasts: These are broadcasts sent by an application to notify other apps of some event or action. For example, an app might send a custom broadcast when a user completes a task or when a new message is received.
Declaring and Implementing a BroadcastReceiver
1. Registering a BroadcastReceiver (In Code)
To receive broadcasts, you need to register the BroadcastReceiver in your app. You can register it either dynamically (in code) or statically (through the app's manifest file).
Dynamically Registering a BroadcastReceiver:
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Handle the broadcast here
String action = intent.getAction();
if (action != null && action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
// Respond to airplane mode change
boolean isAirplaneMode = intent.getBooleanExtra("state", false);
Log.d("Receiver", "Airplane mode changed: " + isAirplaneMode);
}
}
};
@Override
protected void onStart() {
super.onStart();
// Register the receiver to listen for airplane mode changes
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver, filter);
}
@Override
protected void onStop() {
super.onStop();
// Unregister the receiver when the activity is no longer active
unregisterReceiver(receiver);
}
}
In this example, the BroadcastReceiver listens for the airplane mode change (Intent.ACTION_AIRPLANE_MODE_CHANGED). When the airplane mode is toggled, the receiver’s onReceive() method is invoked.
2. Registering a BroadcastReceiver (In the Manifest)
You can also declare the receiver statically in the app's AndroidManifest.xml. This method is used for receiving system-wide broadcasts like when the device is booted or the battery is low.
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
This allows your app to automatically listen for the broadcast even if your app isn't currently running.
Note: When registering in the manifest, you do not need to call registerReceiver() in your code, as the system automatically takes care of it.
3. BroadcastReceiver Example
Here’s a complete example of how to create and use a BroadcastReceiver:
public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This will handle the battery level changes
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
Log.d("BatteryReceiver", "Battery Level: " + level + "%");
}
}
}
In this example, the BatteryReceiver listens for changes in the battery level. When the broadcast is received, the onReceive() method is triggered, and you can extract the battery level.
Intent Filter
An Intent Filter is used to specify the type of broadcast the receiver is interested in. The filter helps match the receiver to a particular event (like a system-wide broadcast).
Here’s how you can set up an IntentFilter:
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
BatteryReceiver receiver = new BatteryReceiver();
registerReceiver(receiver, filter);
In this case, the filter listens for Intent.ACTION_BATTERY_CHANGED, which is a system broadcast for when the battery level or charging status changes.
Important Considerations
-
Life Cycle of BroadcastReceiver: When you register a
BroadcastReceiverdynamically, it is only active as long as the component (activity or service) that registered it is alive. When the component stops, you should unregister the receiver to avoid memory leaks. -
Permissions: Certain broadcasts (like those related to SMS, contacts, etc.) require special permissions in the Android manifest to receive. For example:
<uses-permission android:name="android.permission.RECEIVE_SMS"/> -
Background Execution Limits: Starting from Android 8.0 (API level 26), there are limitations on background services and broadcasts. If your app needs to listen to certain events while in the background, you must ensure that the receiver is registered with the correct context, such as a
JobIntentService.
Conclusion
A BroadcastReceiver is an essential component for apps that need to listen for system-wide or custom events in Android. It enables apps to respond to significant events, such as a change in network connectivity, battery status, or incoming SMS messages. By properly registering and handling broadcasts, developers can create more responsive, interactive apps that stay in tune with system changes without having to constantly poll for them.
Remember to unregister your BroadcastReceiver when it’s no longer needed to avoid memory leaks and unnecessary resource consumption.
0 Comments