Broadcast Receiver in Android

Creating-a-Broadcast-Receiver-in-Android-feature.jpg

While working with Android app development, one of the most important topics that you will come across is the Broadcast Receiver. A Broadcast Receiver in Android is a component that listens for system events and responds whenever significant actions occur on the device. For example, it can happen when the phone starts up, when you get a new SMS, when there’s an incoming call, or when you switch the device to airplane mode. It helps your app to listen to system-wide events or even custom events that are triggered within your own application.

In this blog, you will understand everything about what a Broadcast Receiver in Android is, how it works, and how you can use it to make your applications more interactive. So let’s get started!

Table of Contents

What is a Broadcast Receiver in Android?

Broadcast Receiver in Android is basically a component that receives broadcast messages (known as Intents) from the Android system or other applications. For example, your system may send a message or notification when the device is connected to Wi-Fi, when the battery is running low, or when the screen goes off. Your app can hear these broadcasts and take proper actions.

Key Features of Broadcast Receiver 

Some of the key features of the Broadcast Receiver in Android include:

1. A Broadcast Receiver in Android allows your application to monitor events in your system, such as when the battery is low, when the screen is turned on/off, or your own custom events.

2.  It does not show any screen or design. It only runs in the background to handle events.

3. Your app can still respond to broadcasts even if the user is not actively using it.

4. A Broadcast Receiver is small, and it focuses only on responding to events quickly.

5. It exists only when an event occurs and finishes its work immediately after the event is over.

6. It can be registered either in the AndroidManifest file (static) or in your code (dynamic).

7. It can catch events from the Android system (like Wi-Fi connected) or from your own app (like a file download completed).

Become a Full-Stack Software Engineer
Master frontend and backend development, build real-world projects, and get job-ready with expert mentors.
quiz-icon

Types of Broadcast Receivers in Android

There are mainly two types of Broadcast Receivers in Android. They are:

1. System Broadcast Receivers

A System Broadcast Receiver receives events sent by the Android system itself. They are system-wide events that automatically occur on the device. Android sends a broadcast, e.g., when the battery is low, when the phone is charging, when the screen is on or off, or when the device is on Wi-Fi. With a system Broadcast Receiver registered to your app, it can identify these events and react to them. These events are generated by the Android operating system, not by the developer.

2. Custom Broadcast Receivers

You can make your own Custom Broadcast Receiver to process your own defined events. These broadcasts are sent by your app and not by the Android system. An example of this is when your app is downloading a file in the background. After the download is complete, your app is able to send a custom broadcast. Your other application component, like the user interface, can listen to this broadcast and present a message on the screen that will state “download complete!”. In this case, you are in control of sending the broadcast as well as creating the receiver to listen to the broadcast.

Lifecycle of a Broadcast Receiver in Android

The lifecycle of a Broadcast Receiver in Android is very short and simple compared to other Android components like activities or services. A Broadcast Receiver does not stay active all the time. Instead, it only comes alive when a broadcast event occurs.

When a broadcast occurs, such as a system broadcast like battery low, Wi-Fi connected, or screen on or off, or a custom broadcast, the receiver activates and calls the onReceive() method. Inside this method, you can write code to handle the event, for example, showing a notification, updating the UI, or starting a service.

Once the onReceive() method finishes running, the Broadcast Receiver’s job is done, and it is destroyed. This is why the lifecycle of a Broadcast Receiver in Android is so short. It cannot perform long-running tasks because it only exists for that quick moment when the broadcast is received. If you want to do something that takes more time (like downloading a file), you should hand off the task to a service or a background worker.

In summary:

  • A Broadcast Receiver starts working when an event occurs.
  • It runs using the onReceive() method.
  • After the task is completed, it goes immediately.

How to Create a Broadcast Receiver in Android?

In Android, a Broadcast Receiver in Android is created when you want your application to listen and respond to some events, like when the battery is low, or when the device gets connected to Wi-Fi. In order to create a Broadcast Receiver in Android, you need to follow the steps given below:

Step 1: Create a New Broadcast Receiver Class in Android

At the first step, you have to create a class that extends the BroadcastReceiver class. Inside that class, you have to override the onReceive() method. This method will run whenever your receiver catches an event. 

Code:

Java

Explanation: The above Java code is used to create a Broadcast Receiver that listens for the low battery event. When the system sends the ACTION_BATTERY_LOW broadcast, the onReceive() method runs and displays a small pop-up message that says “Battery is Low!

Get 100% Hike!

Master Most in Demand Skills Now!

Step 2: Register the Receiver

You can register the receiver in two ways:

a. Static Registration (Manifest File)

Here, you have to add the receiver details inside the AndroidManifest.xml file. This way, the receiver remains active and can watch the event, even when your application is not running. It is useful for system-level events like booting the device, battery low, or network changes.

Code:

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BATTERY_LOW"/>
    </intent-filter>
</receiver>

Explanation: The above XML code is used to register MyReceiver in the manifest so that it gets notified about the battery low event. When the battery gets low, Android instructs the receiver to run its onReceive() command.

b. Dynamic Registration (In Code)

You can also register it in your activity or service using an IntentFilter. This method is called dynamic registration, and it only works while your app is running. It gives you more control because you can decide exactly when to start and stop listening to the broadcast.

Code:

Java

You should not forget to unregister the receiver when it is no longer needed (like in onStop() or onDestroy()).

Java

Step 3: Test the Receiver

Now, whenever the battery of your device goes low, your application will notify you with a pop-up message saying “Battery is Low!”. This happens because the Broadcast Receiver is listening to the battery low event actively. As soon as the Android sends that broadcast, your receiver catches it instantly and displays the message to alert you. This helps to make sure that you are already informed about the system changes without opening the app.

Advantages and Limitations of Broadcast Receivers

In this section, we are going to discuss the various advantages and limitations of Broadcast Receivers in Android.

Advantages of Broadcast Receivers

  1. You can make your app react to important system events like low battery, Wi-Fi connection, or the screen turning on and off.
  2. Your application does not need to be open; the Broadcast Receiver can still watch the events and take action.
  3. Broadcast Receivers run only for a short period of time. Therefore, they are unable to use too many system resources.
  4. They also allow different applications or the components of the same application to send and receive messages easily.
  5. You can use them to notify the users about important updates like incoming calls, new messages, or reminders.

Disadvantages of Broadcast Receivers

  1. A Broadcast Receiver works only for a moment when the event occurs. Therefore, it is unable to handle long-running tasks.
  2. If you use a lot of Broadcast Receivers, your application might slow down, or it might drain more battery.
  3. In the newer Android versions, many broadcasts are limited in order to save battery and improve the performance of the device. Hence, not all broadcasts work as before.
  4. Broadcast Receivers cannot show a screen directly; they can only trigger actions like sending a notification.
  5. When the Broadcast Receivers are not used carefully, they can make your application respond to unnecessary events. This affects the stability and security of the application.

Sending and Receiving Broadcast Intents in Android

In Android, broadcasts are sent as intents. An intent is basically a message that can be passed to different parts of the system. When a broadcast intent is sent, it can be received either by the Android system, your own application, or even by other applications if they are set up to listen for it.

Sending a Broadcast Intent

In order to send a broadcast, you have to create an Intent along with a specific action, and then you have to call sendBroadcast(). These actions work like a label that helps receivers to identify what kind of event it is.

Code:

Java

Explanation: In the above Java code, the broadcast is sent with the action com.example.CUSTOM_INTENT.

Receiving a Broadcast Intent

In order to receive a broadcast, you need a Broadcast Receiver that listens to the action you have defined. You can register it either in the AndroidManifest.xml or you can do it dynamically in your code using IntentFilter.

Code:

Java

After that, you can register the Broadcast Receiver dynamically:

Code:

Java

Explanation: The above Java code tells your application to listen to the event named “com.example.CUSTOM_INTENT” and then runs MyReceiver when the event is broadcast.

Best Practices for Using Broadcast Receivers in Android

1. You should always unregister receivers that are dynamically registered when your activity or service is destroyed. If you do not do this, it can cause memory leaks.

2. If you only want to send messages inside your own application, you can use LocalBroadcastManager instead of using system-wide broadcasts. It is faster and more secure.

3. You should not perform heavy tasks inside onReceive(). This is because it runs on the main thread. Instead of this, you should start a background service or use a worker.

4. Since static receivers always respond to system events, they can also drain the battery if they are overused. You should use them only when needed.

5. If your broadcast carries any sensitive or personal data, always use permissions so that only trusted apps can send or receive it.

Real-World Use Cases of Broadcast Receivers in Android

Given below are some of the real-world use cases of Broadcast Receivers in Android:

1. Network state changes: Broadcast receivers are used to detect when the device is connected or disconnected from the internet.

2. Battery monitoring: Your device gets alerts when the battery is low or when you plug into a charger.

3. Incoming calls & SMS detection: You will get to know when a call or text message arrives on the device.

4. Alarm and reminders: It is responsible for triggering notifications or tasks at a scheduled time. 

Conclusion

Broadcast Receivers in Android act like messengers that help your app react to important events that take place in the device or in other applications. They notify you about certain events like battery status, network changes, or even your custom events. By using them the right way, you can make your applications smarter and more attractive.

Level up your career by joining the Full-Stack Development Bootcamp today. Gain hands-on experience with real projects and prepare for tech interviews with industry-ready Full-Stack Interview Questions.

Broadcast Receiver in Android – FAQs

Q1. Can a Broadcast Receiver run without opening the app?

Yes, when it is registered as part of the manifest, it will also run even when the app is not in use.

Q2. Can a Broadcast Receiver handle multiple events at once?

Yes, you can add several actions to it in the IntentFilter.

Q3. Do Broadcast Receivers run on the main thread?

Yes, by default, they run on the main thread, so you should avoid heavy tasks inside them.

Q4. Can a Broadcast Receiver start an activity?

Yes, but you need to set the right flags in the intent for it to work properly.

Q5. What happens if two apps listen to the same broadcast?

Both apps will receive the broadcast unless it’s a private or ordered broadcast.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner