BroadcastReceiver
A BroadcastReceiver is a component in Android that allows an application to listen for and respond to broadcast messages from other applications or the system. These broadcasts can be system-wide events, such as connectivity changes, battery status updates, or custom messages sent by other applications.
Characteristics
– Asynchronous: BroadcastReceivers operate asynchronously, meaning they can respond to broadcasts without blocking the main application thread.
– Lightweight: They are lightweight components, designed to perform a specific task in response to a broadcast message.
– Manifest and Runtime Registration: BroadcastReceivers can be registered in the AndroidManifest.xml file or at runtime within an activity or service.
– Intent Filter: They use intent filters to specify which broadcasts they are interested in, allowing them to listen for specific actions or events.
Examples
– System Broadcasts: Listening for system events such as:
– android.intent.action.BOOT_COMPLETED: Triggered when the device finishes booting.
– android.net.conn.CONNECTIVITY_CHANGE: Triggered when network connectivity changes.
-
Custom Broadcasts: An application can send custom broadcasts that other applications can listen for. For example, an app might send a broadcast to notify other components of a data update:
java
Intent intent = new Intent("com.example.UPDATE_DATA");
sendBroadcast(intent); -
Manifest Declaration: A BroadcastReceiver can be declared in the AndroidManifest.xml:
xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.UPDATE_DATA" />
</intent-filter>
</receiver> -
Runtime Registration: A BroadcastReceiver can also be registered at runtime:
java
BroadcastReceiver myReceiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter("com.example.UPDATE_DATA");
registerReceiver(myReceiver, filter);


