Broadcast Receiver in Android With Example
Last Updated :
02 Jan, 2025
Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers allow us to register for the system and application events, and when that event happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers:
- Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even if the app is closed.
- Dynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized.
Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so we have implemented dynamic receivers in our sample project given below. There are some static fields defined in the Intent class which can be used to broadcast different events. We have taken a change of airplane mode as a broadcast event, but there are many events for which broadcast register can be used. Following are some of the important system-wide generated intents:-
Intent
| Description Of Event
|
|---|
| android.intent.action.BATTERY_LOW : | Indicates low battery condition on the device. |
| android.intent.action.BOOT_COMPLETED | This is broadcast once after the system has finished booting |
| android.intent.action.CALL | To perform a call to someone specified by the data |
| android.intent.action.DATE_CHANGED | Indicates that the date has changed |
| android.intent.action.REBOOT | Indicates that the device has been a reboot |
| android.net.conn.CONNECTIVITY_CHANGE | The mobile network or wifi connection is changed(or reset) |
| android.intent.ACTION_AIRPLANE_MODE_CHANGED | This indicates that airplane mode has been switched on or off. |
The two main things that we have to do in order to use the broadcast receiver in our application are:
Creating the Broadcast Receiver:
class AirplaneModeChangeReceiver:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// logic of the code needs to be written here
}
}
Registering a BroadcastReceiver:
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
// receiver is the broadcast receiver that we have registered
// and it is the intent filter that we have created
registerReceiver(receiver,it)
}
Example
Below is the sample project showing how to create the broadcast Receiver and how to register them for a particular event and how to use them in the application.
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 .
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Working with the MainActivity file
Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}
Kotlin
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
// register the receiver in the main activity in order
// to receive updates of broadcasts events if they occur
lateinit var receiver: AirplaneModeChangeReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
receiver = AirplaneModeChangeReceiver()
// Intent Filter is useful to determine which apps wants to receive
// which intents,since here we want to respond to change of
// airplane mode
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
// registering the receiver
// it parameter which is passed in registerReceiver() function
// is the intent filter that we have just created
registerReceiver(receiver, it)
}
}
// since AirplaneModeChangeReceiver class holds a instance of Context
// and that context is actually the activity context in which
// the receiver has been created
override fun onStop() {
super.onStop()
unregisterReceiver(receiver)
}
}
Step 4: Create a new 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 AirplaneModeChangeReceiver . Below is the code for the AirplaneModeChangeReceiver 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.provider.Settings;
import android.widget.Toast;
public class AirplaneModeChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
Kotlin
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
// AirplaneModeChangeReceiver class extending BroadcastReceiver class
class AirplaneModeChangeReceiver : BroadcastReceiver() {
// this function will be executed when the user changes his
// airplane mode
override fun onReceive(context: Context?, intent: Intent?) {
// intent contains the information about the broadcast
// in our case broadcast is change of airplane mode
// if getBooleanExtra contains null value,it will directly return back
val isAirplaneModeEnabled = intent?.getBooleanExtra("state", false) ?: return
// checking whether airplane mode is enabled or not
if (isAirplaneModeEnabled) {
// showing the toast message if airplane mode is enabled
Toast.makeText(context, "Airplane Mode Enabled", Toast.LENGTH_LONG).show()
} else {
// showing the toast message if airplane mode is disabled
Toast.makeText(context, "Airplane Mode Disabled", Toast.LENGTH_LONG).show()
}
}
}
Output:
Similar Reads
Broadcast Receiver in Android With Example
Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers al
5 min read
TextView in Android with Example
TextView is a simple widget that is seen in every android application. This widget is used to display simple text within the android application. We can add custom styling to the text that we have to show. In this article, we will take a look at How to create a simple Text View in an android applica
2 min read
ParticleView in Android with Examples
ParticleView is an animation library and animations help to gain the attention of the user so it is best to learn it. It is the custom Android view that helps to display a large number of fairies. [video loading="lazy" mp4="https://media.geeksforgeeks.org/wp-content/uploads/20240725161641/particlevi
2 min read
Services in Android with Example
Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at t
10 min read
Data Binding in Android with Example
In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. What we are going to build in this article?Here is a sample video of what we are going to build in this
4 min read
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passi
6 min read
Context Menu in Android with Example
In Android, there are three types of menus available to define a set of options and actions in the Android apps. The lists of menus in Android applications are the following: Android options menuAndroid context menuAndroid popup menuHere in this article let's discuss the detail of the Context Menu.
4 min read
Jetpack LiveData in Android with Example
Android Jetpack is a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across Android versions and devices so that developers can focus on the code they care about. Here, we are going to implement Jetpack Live Data in Android
4 min read
Intent Service in Android with Example
An IntentService is a subclass of Service in Android that is used to handle asynchronous requests (expressed as "Intents") on demand. It runs in the background and stops itself once it has processed all the intents that were sent to it. An IntentService in Java and Kotlin: C/C++ Code class MyIntentS
5 min read
OpenIntents in Android with Example
OI refers to the "OpenIntents" project in Android are a way for one app to request an action from another app. This can be done using either explicit or implicit intents, allowing them to share functionality. The OpenIntents project provides a set of commonly-used intents that can be used by develop
4 min read
Deep Linking in Android with Example
Deep Linking is one of the most important features that is used by various apps to gather data inside their apps in the form of a URL link. So it becomes helpful for the users from other apps to easily share the data with different apps. In this article, we will take a look at the implementation of
7 min read
CustomArrayAdapter in Android with Example
In Android, ArrayAdapters are used for populating and controlling the ListView and Spinners. ArrayAdapter by default provides ListItems that include only single information or single TextView. In order to have a more complex layout that includes multiple information in a single ListItem such as imag
5 min read
Android Listview in Java with Example
A ListView is a type of AdapterView that displays a vertical list of scroll-able views and each view is placed one below the other. Using an adapter, items are inserted into the list from an array or database. For displaying the items in the list method setAdaptor() is used. setAdaptor() method conj
3 min read
Line Graph View in Android with Example
If you are looking for a view to represent some statistical data or looking for a UI for displaying a graph in your app then in this article we will take a look on creating a line graph view in our Android App using the GraphView library. What we are going to build in this article? We will be build
3 min read
Android Sensors with Example
In our childhood, we all have played many android games like Moto Racing and Temple run in which by tilting the phone the position of the character changes. So, all these happen because of the sensors present in your Android device. Most Android-powered devices have built-in sensors that measure mot
4 min read
Exceptions in Android with Example
Exceptions in Android refer to abnormal events or conditions that occur during the execution of an app, which can cause the app to crash or behave unexpectedly. There are several types of exceptions that can occur in Android, including: Checked Exceptions: These are exceptions that are checked by th
3 min read
Internal Storage in Android with Example
The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal
5 min read
Notifications in Android with Example
Notification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android's UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user ab
5 min read
Synchronization in Android with Example
In Android, synchronization refers to the process of ensuring that data stored in multiple locations is the same and up-to-date. This can be achieved through various methods such as using the built-in Android synchronization adapters, or by manually implementing synchronization using the Android Syn
5 min read