How to Use LocalBroadcastManager in Android?
Local Broadcast Manager is one of the most important features which is seen in most of the applications which we used. This feature generally works in the background and we cant see that. The BroadCast Manager will notify us when a specific event occurs. For example when we are subscribed to any of the courses on GeeksfoGeeks when there is an update or contest being conducted in that course then we are notified through email regarding that event. In that place, BroadCast Manager is used which notifies users with a message, mail, or any other format regarding a specific event. In this article, we will take a look at using this Broadcast Manager in our Android App.
How to use Broad Cast Manager in Android?
To use Broad Cast Manager in our Android app, the process of using it is divided into two types in which firstly we have to register our broadcast and then receive updates from the same broadcast.
Step 1: Registering a Broadcast
For performing a specific action using Broadcast manager we have to firstly register our Broadcast and then only we can use this broadcast to receive updates. There are 2 ways to register our broadcast we can register it in our Android Manifest file or in our Activity where we want to receive its updates.
Step 2: Receiving the updates from Broadcast
This step is used to receive the updates which we will send through our Broadcast Manager after performing a certain action inside our application. For receiving the updates we will be using onRecieve() method to receive the update.
What we are going to build?
We will be building a simple application in which we will be sending our data using broadcast manager on clicking the button. Below is the video in which we will get to see what we are going to build in this article.
Step by Step Implementation of Broadcast Manager
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 3: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Now run your app and see the output of the app.