Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Broadcast Receiver 
3.
Using Broadcast Receivers
3.1.
Creating the Broadcast Receiver
3.2.
Registering the Broadcast Receiver
4.
Example
5.
FAQs
6.
Key Takeaways  
Last Updated: Mar 27, 2024

Android Broadcast Receivers

Author Pradeep Kumar
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this blog, we will look into Android Broadcast Receivers. We will discuss how Broadcast Receivers are created and registered. Additionally, we will look at the different kinds of Broadcast Receivers and their uses.

In this article, we will be using the Android Studio application, so in case you haven't yet set up the application on your system, you can check out this article.

Broadcast Receiver 

Broadcast is a message that can be received by any app. The system sends out various broadcasts in response to system events, such as when the system boots up, when the airplane mode is enabled, when the device is put on silent, or upon receiving an incoming call or a text message. To respond to these system events, Broadcast Receivers are used. Using Broadcast Receivers, you can register for any system or custom event. When that event happens, then the corresponding receiver will get notified. 

Following are the two main types of Broadcast Receivers:

  • Static Broadcast Receivers: They work even when the app is closed. Static Broadcast Receivers are declared inside the AndroidManifest.xml file.
  • Dynamic Broadcast Receivers: These receivers don't work when the app is closed. They only function when the app is either in the active state or is minimized but still present in the background.

Let's discuss some of the common system intents and their respective functions. Here is a list of some important system intents:

  • android.intent.ACTION_AIRPLANE_MODE_CHANGED: As the name suggests, this intent shows if the airplane mode is enabled or disabled. 
  • android.intent.action.BATTERY_LOW: This broadcast is sent when the battery of the device is low.
  • android.intent.action.BOOT_COMPLETED: It shows that the system boot has been completed.
  • android.net.conn.CONNECTIVITY_CHANGE: It reflects the change in the connectivity of mobile data or wifi connection. 
  • android.intent.action.DATE_CHANGED: This shows the change in date
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Using Broadcast Receivers

Two main steps for using Broadcast Receivers in an android application are creating and registering the Broadcast Receiver. Let's discuss the syntax of both functions:

Creating the Broadcast Receiver

To create a new Broadcast Receiver, we need to create a new class that extends the Broadcast Receiver class. Then you can override the onReceive function of the class. 

Syntax

class AirplaneModeReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        // body of the function
    }
}

Registering the Broadcast Receiver

To Register a Broadcast Receiver, a new Intent Filter is created with the specified intent.

Syntax

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
    /*
    registering the receiver
    Here the parameter it that we are passing along with our AirplaneModeReceiver()
    is the intent filter that we just created.
    */
    registerReceiver(AirplaneModeReceiver(), it)
}

In the next section, we will discuss an example of how we can use Broadcast Receivers in our application.

Also see, android operating system

Example

In this example, we will register a Broadcast Receiver for the intent Airplane Mode. The receiver will get notified when the Airplane Mode is enabled or disabled. 

First, we need to create a new project in Android Studio by selecting the empty activity option. One of the most important files of any android project is its activity_main.xml file, which would look something like this:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

In this example, we are working with Dynamic Broadcast Receivers; therefore, you don't need to change the activity_main.xml file. 

Now we will create a new Kotlin file with the name "AirplaneModeReceiver" inside the same directory as your MainActivity.kt file. In this file, we will create the Broadcast Receiver

AirplaneModeReceiver.kt

import android.content.Context
import android.content.BroadcastReceiver
import android.widget.Toast
import android.content.Intent

//  AirplaneModeReceiver class extending BroadcastReceiver class
class AirplaneModeReceiver : BroadcastReceiver() {

    // upon turning on/off the airplane mode, this function will be executed
    override fun onReceive(context: Context, intent: Intent) {

        val name_value = "state" // parameter value of name that we will pass to getBooleanExtra
        val default_value = false // default value for isEnabled
        // getting the state value
        val is_enabled = intent.getBooleanExtra(name_value, default_value) ?: return

        // value of the text that will be shown on the screen
        var show_text = "Airplane Mode is Off"

        // check if airplane mode is on or not
        if (is_enabled) {
            // change the value of show_text if the mode is enabled.
            show_text = "Airplane Mode is On"
        }

        // duration specifies the amount of time that the text will remain on the screen for
        val duration = Toast.LENGTH_LONG
        Toast.makeText(context, show_text, duration).show()
    }
}

Now we will go to the MainActivity.kt file, where we would write the code for registering our Broadcast Receivers. 

MainActivity.kt

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.content.IntentFilter
import android.os.Bundle

// Main Activity class extending AppCompatActivity
class MainActivity : AppCompatActivity() {

    // registering the receiver in mainActivity
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Creating an Intent Filter for Airplane Mode.
        IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
            /*
            registering the receiver
            Here the parameter it that we are passing along with our AirplaneModeReceiver()
            is the intent filter that we just created.
            */
            registerReceiver(AirplaneModeReceiver(), it)
        }
    }
}

Output

When the airplane mode is enabled, a text saying "Airplane Mode is On" is shown on the screen, which looks like this: 

Upon turning off the airplane mode, a text saying "Airplane Mode is Off" is shown on the screen, which looks like this: 

FAQs

  1. What is the use of an Intent?
    An Intent is a messaging object that we can use to request a specific action from another app component. We can transfer data from one activity to another using Intent.
     
  2. What kind of information does the AndroidManifest.xml file store?
    The AndroidManifest.xml file contains critical information about the Android app such as - package name, activity names, main activity(the app's entry point), Android version support, permissions, etc.
     
  3. Can we restrict broadcast to only the current app?
    Yes, broadcasts can be restricted to the current application by defining them as local broadcasts.

Check this out : usb debugging

Key Takeaways  

Cheers if you reached here!!!

In this blog, we learned about Broadcast Receivers in Android. We discussed how Broadcast Receivers could be created and registered in an android application. After reading this blog, I believe you will be able to work with Android Broadcast Receivers smoothly. 

In this article, we have used Intent and Intent filters. To learn more about them, you can check out our other article on the topic of Android Intents. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website.

Previous article
What is Android System WebView?
Next article
Android Intents
Live masterclass