Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Use LocalBroadcastManager in Android?

  • Last Updated : 30 Apr, 2021

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. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idRLView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--text view for receiving our data updates
        using broad cast manager-->
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:text="Welcome"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/black"
        android:textSize="30sp" />
  
    <!--button for sending the updated data with 
        the help of broad cast manager-->
    <Button
        android:id="@+id/idBtnStartBroadCast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHeading"
        android:layout_centerInParent="true"
        android:layout_marginTop="30dp"
        android:text="Send BroadCast"
        android:textAllCaps="false" />
  
</RelativeLayout>

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.

Java




import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
  
public class MainActivity extends AppCompatActivity {
      
    // creating a variable for 
    // our text view and button
    private TextView headingTV;
    private Button sendBroadCastBtn;
      
    // on below line we are creating a new broad cast manager.
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        // we will receive data updates in onRecieve method.
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("message");
            // on below line we are updating the data in our text view.
            headingTV.setText(message);
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        headingTV = findViewById(R.id.idTVHeading);
        sendBroadCastBtn = findViewById(R.id.idBtnStartBroadCast);
          
        // on below line we are registering our local broadcast manager.
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter("custom-action-local-broadcast"));
          
        // on below line we are adding click listener to our button
        sendBroadCastBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // inside on click we are calling the intent with the action.
                Intent intent = new Intent("custom-action-local-broadcast");
                // on below line we are passing data to our broad cast receiver with key and value pair.
                intent.putExtra("message", "Welcome \n to \n Geeks For Geeks");
                // on below line we are sending our broad cast with intent using broad cast manager.
                LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);
            }
        });
    }
}

Now run your app and see the output of the app. 

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!