Broadcast Receiver

Broadcast Receiver in Android Studio with Example

A broadcast receiver is an Android component that allows you to send and receive events from your Android system or application. When an event occurs, the Android runtime notifies all registered applications. It’s used for asynchronous inter-process communication and operates similarly to the publish-subscribe design pattern.

In Android, broadcast refers to system-wide events such as when the device boots up, receives a message, receives incoming calls, or goes into airplane mode, among other things. To respond to these system-wide events, broadcast receivers are used. Broadcast Receivers allow us to register for system and application events, and the register receivers are notified when the event occurs. 

Output:

Broadcast Receivers are divided into two categories:

  1. Static Broadcast Receivers: It defined in the manifest file and work even if the app is closed.
  2. Dynamic Broadcast Receivers: These receivers only function when the app is open or minimised.

The broadcast register can be used for a variety of events. Some of the most important system-wide created intents are as follows:-

                       IntentDescription Of Event
android.intent.action.BATTERY_LOW :This indicates a low battery condition on the device.
android.intent.action.BOOT_COMPLETEDThis is broadcast once after the system has completed booting
android.intent.action.CALLTo make a phone call to someone specified in the data
android.intent.action.DATE_CHANGED This indicates that the date has changed
android.net.conn.CONNECTIVITY_CHANGEThe mobile network or wifi connection has been altered (or reset)
android.intent.ACTION_AIRPLANE_MODE_CHANGEDThis indicates the on or off of the airplane mode.

Broadcast Receiver Example

The sample project below demonstrates how to create a broadcast receiver, register it for a specific event, and use it in the application.

Step 1: Create a New Project in Android Studio.

Step 2: Working with the activity_main.xml file.

<?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="Developersdome"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity file.

package com.sagar.broadcastreceiver

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

class MainActivity : AppCompatActivity() {


    lateinit var receiver: AirplaneMode
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        receiver = AirplaneMode()

        IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {

            registerReceiver(receiver, it)
        }
    }

    override fun onStop() {
        super.onStop()
        unregisterReceiver(receiver)
    }
}

Step 4: Create a new kotlin class

Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Kotlin File/Class and name the files as AirplaneMode. Below is the code of AirplaneMode.kt class.

package com.sagar.broadcastreceiver

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

class AirplaneMode : BroadcastReceiver() {

    // this function will be excecuted when the user changes the status of airplane mode
    override fun onReceive(context: Context?, intent: Intent?) {


        // if getBooleanExtra contains null value,it will directly return back
        val isAirplaneModeEnabled = intent?.getBooleanExtra("state", false) ?: return

        if (isAirplaneModeEnabled) {

            Toast.makeText(context, "Airplane Mode On", Toast.LENGTH_LONG).show()
        } else {

            Toast.makeText(context, "Airplane Mode Off", Toast.LENGTH_LONG).show()
        }
    }
}

Step 5: Add receiver to the AndroidManifest.xml file as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sagar.broadcastreceiver">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BroadcastReceiver">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".AirplaneMode"/>
    </application>

</manifest>

Run the application now. You will get the output shown in the output section.

  • We hope that this guide will assist you in understanding all about the concepts of Broadcast Receiver in Android. We have concentrated on making a basic, meaningful and easy-to -learn guide to the concepts of Broadcast Receiver with suitable examples. Still if you have any problems regarding this, please post them in the comments section, we will be glad to assist you.

You might also like:

Using DiffUtil in Android RecyclerView Example

Android cardView | Android Recyclerview using cardView

Leave a Reply