Android Studio – 36 – Broadcast Receivers in Android

Broadcast receivers are a key component in Android app development, allowing apps to receive and respond to system-wide or app-specific broadcast messages. These messages can originate from various sources, such as the Android system, other apps, or even the app itself. Broadcast receivers are crucial for listening to and reacting to events, enabling your app to perform actions in response to changes in the environment or user interactions. In this guide, we will explore the concept of broadcast receivers, their significance in Android development, and how to create and manage them using Android Studio, accompanied by code examples and commands for illustration.

Understanding Broadcast Receivers

Broadcast receivers are components that enable your app to receive and respond to broadcast messages. These messages are often referred to as “intents” in Android. Broadcast receivers are used for various purposes, such as:

  1. System Events: Listening for system events like network connectivity changes, battery status, screen on/off, and device boot.
  2. Custom Events: Defining custom broadcast events within your app to communicate between different components, even if they are running in separate processes.
  3. External Events: Reacting to events from other apps or external sources, such as notifications or messages.
  4. Scheduled Tasks: Using alarms to schedule tasks or notifications at specific times or intervals.

Types of Broadcast Receivers

Android supports two types of broadcast receivers:

  1. Static Broadcast Receivers: These receivers are declared in the AndroidManifest.xml file and are registered at app installation time. They can listen for system-level events, but they cannot be dynamically registered or unregistered during runtime.
  2. Dynamic Broadcast Receivers: Dynamic receivers are registered and unregistered at runtime using Java code. They provide more flexibility and can respond to events based on specific conditions within your app.

Creating and Managing Broadcast Receivers in Android Studio

Let’s explore how to create and manage broadcast receivers in Android Studio:

1. Create a BroadcastReceiver Class:

Start by creating a new Java class that extends BroadcastReceiver. Override the onReceive method to define the actions you want to take when the receiver receives a broadcast.

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Handle the broadcast message here
        String action = intent.getAction();

        if (action != null && action.equals("my_custom_action")) {
            // Perform specific action for your custom broadcast
        }
    }
}
2. Register a Dynamic BroadcastReceiver:

To register a dynamic broadcast receiver, you need to use the registerReceiver method in your activity or service.

MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("my_custom_action");

// Register the receiver
registerReceiver(receiver, filter);
3. Declare a Static BroadcastReceiver (Optional):

To declare a static broadcast receiver in your AndroidManifest.xml file, use the <receiver> element. This receiver will be automatically registered when your app is installed.

<receiver
    android:name=".MyReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="my_custom_action" />
    </intent-filter>
</receiver>
4. Send a Broadcast:

To send a broadcast message, create an Intent with the appropriate action and extras (if needed) and use the sendBroadcast method.

Intent broadcastIntent = new Intent("my_custom_action");
broadcastIntent.putExtra("extra_key", "extra_value");

sendBroadcast(broadcastIntent);
5. Unregister a Dynamic BroadcastReceiver:

To unregister a dynamic broadcast receiver, call unregisterReceiver with the receiver instance.

unregisterReceiver(receiver);

Example: Implementing a Broadcast Receiver

Here’s an example of implementing a simple broadcast receiver:

Create the BroadcastReceiver Class:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (action != null && action.equals("my_custom_action")) {
            String extraValue = intent.getStringExtra("extra_key");
            if (extraValue != null) {
                // Handle the broadcast message and extra data
                Toast.makeText(context, "Received Broadcast: " + extraValue, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Register the Dynamic BroadcastReceiver:In your activity or service, register the dynamic broadcast receiver:

MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("my_custom_action");

// Register the receiver
registerReceiver(receiver, filter);

Send a Broadcast:Send a broadcast message from any part of your app:

Intent broadcastIntent = new Intent("my_custom_action");
broadcastIntent.putExtra("extra_key", "Hello, Broadcast Receiver!");

sendBroadcast(broadcastIntent);

In this example, the MyReceiver class listens for the “my_custom_action” broadcast and displays a Toast message with the received extra data.

Conclusion

Broadcast receivers are essential components in Android app development for listening to and responding to broadcast messages. They enable apps to react to system events, custom events, and external events, enhancing the app’s functionality and user experience. By understanding the types of broadcast receivers, creating receiver classes, and registering them dynamically or statically, you can effectively integrate broadcast receivers into your Android apps using Android Studio.