Open In App

Local Broadcast Manager in Android using Jetpack Compose

Improve
Improve
Like Article
Like
Save
Share
Report

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 does not appear in the application. The Broadcast Manager will notify us when a specific event occurs. For example when we are subscribed to any of the courses on Geeks for Geeks 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 Local Broadcast Manager in Android Applications using Jetpack Compose.

Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only available in Kotlin. It uses features such as coroutines, and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support Kotlin.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a New Color to the Color.kt File

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Working with the MainActivity.kt File

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.example.newcanaryproject.ui.theme.*
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying
                // background color for our application
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
                        // in scaffold we are specifying top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying text
                                        // to display in top app bar.
                                        text = "Local Broad Cast Manager",
                                        // on below line we are specifying modifier
                                        // to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
                                        // on below line we are specifying text alignment.
                                        textAlign = TextAlign.Center,
                                        // on below line we are specifying color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling custom list
                        // view function to display custom listview.
                        broadcastManager(LocalContext.current)
                    }
                }
            }
        }
    }
}
 
@Composable
fun broadcastManager(ctx: Context) {
    // on below line we are creating a variable for broad cast manager status.
    val broadCastMsg = remember {
        mutableStateOf("Welcome")
    }
    // on below line we are creating a new broad cast manager.
    val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        // we will receive data updates in onReceive method.
        override fun onReceive(context: Context?, intent: Intent) {
            // Get extra data included in the Intent
            val message = intent.getStringExtra("message")
            // on below line we are updating the data in our text view.
            broadCastMsg.value = message!!
        }
    }
    // on below line we are registering our local broadcast manager.
    LocalBroadcastManager.getInstance(ctx).registerReceiver(
        broadcastReceiver, IntentFilter("custom-action-local-broadcast")
    )
    // on below line we are creating a column
    Column(
        // on below line we are specifying modifier
        // and setting max height and max width for our column
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth()
            // on below line we are
            // adding padding for our column
            .padding(5.dp),
        // on below line we are specifying horizontal
        // and vertical alignment for our column
        horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center
    ) {
        // on below line we are creating a simple text for displaying a text
        Text(
            text = "Local Broad Cast Manager in Android",
            textAlign = TextAlign.Center,
            fontWeight = FontWeight.Bold,
            fontSize = 20.sp,
            color = greenColor
        )
        // on below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
        // on below line we are creating a text to display broad cast manager message.
        Text(
            text = broadCastMsg.value,
            textAlign = TextAlign.Center,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(4.dp)
        )
        // on below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
        // on below line we are creating a button for sending broadcast message.
        Button(onClick = {
            // inside on click we are calling the intent with the action.
            val intent = 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\nto\nGeeks For Geeks")
            // on below line we are sending our broad cast with intent using broad cast manager.
            LocalBroadcastManager.getInstance(ctx).sendBroadcast(intent)
        }) {
            // on below line we are specifying text for our button.
            Text(text = "Send Broadcast")
        }
    }
}


Now run your application to see the output of it.

Output:



Last Updated : 28 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads