Broadcast Receiver in Android with Example

When a device wakes up, receives a message, receives an incoming call, switches to aeroplane mode, or initiates any other system-wide action, it is said to have been broadcast in the context of Android. These system-wide events are handled by broadcast receivers. When a system or application event occurs, broadcast receivers enable us to register for it so that we can be notified when it does. Broadcast receivers can be broadly divided into two categories:

  • Static Broadcast Receivers: These receiver types are listed in the androidmanifest.xml file and continue to function even when the app is dismissed.
  • Dynamic Broadcast Receivers: Only the active or minimised version of the app is compatible with these receivers.

Since the majority of broadcasts may only be received by dynamic receivers as of API Level 26, we have included active receivers in the sample project shown below. Intent's static fields can be utilised to broadcast a variety of events because they are defined there. A change in aeroplane mode has been considered a broadcast event, although there are numerous other events that can also be recorded in the broadcast register. Several significant system-wide produced intents are listed below: -

Following is a list of some of the important intents:

  1. android.intent.action.BATTERY_LOW : It indicates that the smartphone has a low battery.
  2. android.intent.action.BOOT_COMPLETED : After the machine has fully booted, this is transmitted once.
  3. android.intent.action.CALL : It is used to make a call to the person listed in the data.
  4. android.intent.action.DATE_CHANGED : It signals a new date has been set.
  5. android.intent.action.REBOOT : It demonstrates that the machine has been restarted.
  6. android.net.conn.CONNECTIVITY_CHANGE : The wifi or mobile network connection has been altered (or reset)
  7. android.intent.ACTION_AIRPLANE_MODE_CHANGED : This shows whether aeroplane mode is currently on or off.

Using the broadcast receiver in our programme requires two basic steps, which are as follows:

Establishing the Broadcast Receiver

class AirplaneModeChangeReceiver:BroadcastReceiver() {
       override fun onReceive(context: Context?, intent: Intent?) {
            // we have to write the logic of the code here
      }
}

Creating a BroadcastReceiver Account

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
                     // Receiver is the intent filter that we have established 
                    // and is the broadcast receiver that we have registered.
registerReceiver(receiver,it)
      }

Example:

The example project that demonstrates how to establish a broadcast receiver, register it for a specific event, and use it in an application is provided below.

Step 1: Start a New Project

Step 2: Using the file activity main.xml

The following code should be referenced in the activity main.xml file. The activity main.xml file's source code is shown below.

XML Code:

<?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: Manipulating the MainActivity file

The following code may be found in the MainActivity file. The MainActivity file's source code is shown below. Inside the code, comments are added to help the reader comprehend it better.

Kotlin Code:

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


class MainActivity :AppCompatActivity() {


	// In order to receive notifications of broadcast events as they happen, 
	// register the receiver in the primary activity.
	lateinit var receiver1 :AirplaneModeChangeReceiver
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)


		receiver1 = AirplaneModeChangeReceiver()


		// Since we are here to respond to the changing of aeroplane mode,
		// intent filtering is useful to decide which apps
		// wish to receive which intents.
		IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
			// The intent filter that we recently developed 
			// is supplied as a parameter when registering the receiver 
			// with the registerReceiver() function.
			registerReceiver(receiver1, it)
		}
	}


	// due to the fact that the AirplaneModeChangeReceiver class keeps 
	// an instance of Context, and that context is the activity context 
	// where the receiver was formed.
	override fun onStop() {
		super.onStop()
		unregisterReceiver(receiver1 )
	}
}

Java Code:

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


public class MainActivity extends AppCompatActivity {


	AirplaneModeChangeReceiver airplaneModeChangeReceiver1 = new AirplaneModeChangeReceiver();


	@Override
	protected void onCreate(BundlesavedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	@Override
	protected void onStart() {
		super.onStart();
IntentFilter filter1 = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		registerReceiver(airplaneModeChangeReceiver1, filter1 );
	}


	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(airplaneModeChangeReceiver1 );
	}
}

Step 4: Make a brand-new class.

Go to app >> java >> the name of the package (where the MainActivity is present) >> right-click >> New >> Kotlin File/Class and give the files the name AirplaneModeChangeReceiver. The code for the AirplaneModeChangeReceiver file is shown below. Inside the code, comments are added to help the reader comprehend it better.

Kotlin Code:

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


// AirplaneModeChangeReceiver class extends the class BroadcastReceiver
class AirplaneModeChangeReceiver1 :BroadcastReceiver() {


	// When the user switches to aeroplane mode
	// , this method will be called.
	override fun onReceive(context: Context?, intent: Intent?) {
		
		// In this scenario, the broadcast's information is contained in 
		// the intent, which is changing of aircraft mode.


		// If the value of getBooleanExtra is null, it will immediately return.
		val isAirplaneModeEnabled1 = intent?.getBooleanExtra("state", false) ?: return
		
		// determining whether or not aeroplane mode is activated
		if (isAirplaneModeEnabled1) {
			// if aeroplane mode is activated, displaying the toast message.
			Toast.makeText(context, "Airplane Mode is Enabled", Toast.LENGTH_LONG).show()
		} else {
			// if aeroplane mode is not enabled, 
                        // displaying the toast message.
			Toast.makeText(context, "Airplane Mode is Disabled", Toast.LENGTH_LONG).show()
		}
	}
}

Java Code:

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(Contextcontext, Intent intent) {


		if (isAirplaneModeOn1 (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 isAirplaneModeOn1 (Contextcontext) {
		return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
	}
}

Output:

Broadcast Receiver in Android with Example Broadcast Receiver in Android with Example

Related Topics

Jetpack Architecture Components in Android

A collection of software elements, libraries, tools, and instructions is called Android Jetpack. It is available to assist in creating reliable Android applications. Jetpack, which was introduced by Google in...

8 minutes read.

Button Widget in Android Tutorial

Explanation: Button is a widget under Buttons section which is used to execute specific code. Example: XML file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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">     <Button         android:id="@+id/button"         android:layout_width="wrap_content"    ...

1 minute read.

Android Styles and Themes

Android styles allow you to design the appearance (for example, colors, size, and fonts) of Android UI components from XML resource files. With this method, you only need to set...

5 minutes read.

How to reduce the size of APK in Android

What exactly is an APK file? The full form of APK is Android Package Kit. It is the Android operating system's application file format. We use Android Studio to generate APK...

7 minutes read.

Android EditText

In Android, EditText is a UI widget utilized to allow the user to input or change the text. While using the EditTextwidget in your Android application, you need to use...

4 minutes read.

Android Project Folder Structure

JetBrains community developed Android Studio, the official IDE (Integrated Development Environment) for Android app development and is freely distributed by Google. After the complete Android Architecture setup, we can construct an...

4 minutes read.

Broadcast Receiver in Android with Example

When a device wakes up, receives a message, receives an incoming call, switches to aeroplane mode, or initiates any other system-wide action, it is said to have been broadcast in...

5 minutes read.

Different Ways to Create aar File in Android Studio

A file called an Android archive file (*.aar) can be created using Android Studio and comprises classes and methods that use related files and classes for Android. The Android library...

4 minutes read.

How to Generate QRCode in Android?

Many apps use QR codes to show data in a way that is machine-readable. Data is represented using these codes in a secure manner such that only computers, not humans,...

4 minutes read.

AdapterViewFlipper in Android with Example

The AdapterViewFlipper class, a subclass of the ViewAnimator class, is what we use to switch from two or multiple views when only one is present at a time. The AdapterViewFlipper...

10 minutes read.

Difference between android developer and web

From a small business to a big firm, every organization in the world of technology requires a digital market presence and only mobile applications and websites/web applications provide for digital...

4 minutes read.

Android Date picker example

How to pick date from the user in Android? Write an android example to pick date from the user and display it. Android provides control for the user to pick a date...

3 minutes read.

How to insert an email in android application in android version 8

Email Address Insertion It is used to insert email adrress from the user in the android application.The only point of difference between an EditText and an Emailtext is that EmailText consisits...

1 minute read.

Creating a Calendar View App in Android

This article demonstrates how to make an Android application that uses CalendarView to display the Calendar. It also provides the option to pick the current date and view the date....

3 minutes read.

Android TextView

Widgets are user interface (UI) elements that help users to interact with Android applications. It is one of many equipments that can be used to improvise the user interface of...

4 minutes read.

Android ScrollView

A ScrollView is a view group that is used to create vertically scrollable views in an android application. Only a single direct child can be contained by ScrollView. For placing...

5 minutes read.

How to show image on an android application

ImageView Widget in Android What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets   Explanation: Image View widget is used...

2 minutes read.

What is Android Studio

Android Studio powered by the IntelliJ platform is an integrated development environment (IDE) and is officially recognized for developing androidapplications. Its foundation lies on JetBrains' IntelliJ IDEA and is specialized...

3 minutes read.

Android Toast

Android is one of the most successful operating systems available in today's world. It is an open-source phone platform, compatible with almost all the devices. There are numerous features and...

3 minutes read.

Top Programming Languages for Android Development

For mobile apps, there are so many programming languages. You would need to spend days simply researching if you had to pick one from a list of 30 coding languages...

8 minutes read.