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

Android Activity

What is an Activity? Android Activity is a screen in the user interface of an Android application. In this way, Android activity is very similar to the desktop application window. An...

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.

Android Tutorial

This Android tutorial will provide you with all the concepts that will be beneficial for both beginners and advanced-level students or candidates. You can learn this tutorial to begin your...

6 minutes read.

Android Navigation Drawer

A sliding menu used to show important links in the Android Application is called Navigation Drawer. The navigation drawermakes it easier to navigate between the fragments. It is not displayed...

5 minutes read.

Android RecyclerView

RecyclerView is a ViewGroup brought to AndroidStudio as successor to ListView and GridView. These are all improvements and are included in the latest v7 support package. It was written to...

8 minutes read.

How to crop Image from Camera and Gallery in Android?

In this tutorial, we'll learn how to crop photos in the Android Gallery and Camera. There is no crop feature in this project, contrary to what was covered in the...

5 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 Broadcast Receivers

Android applications can send or receive broadcast messages from the Android operating system and other Androidapplications, like the publish-subscribe design pattern. When an event of interest happens,these broadcasts are sent. For...

4 minutes read.

Android ListView

A kind of AdapterView that displays a vertical list of scrollable views, each of which is laid out below each other is called ListView. Using adapters, items are inserted into...

4 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.

How to insert the mobile number on an android application using EditText

Number Insertion in android application: Sometimes while dealing with numbers, we don't want to insert any string inside an number so, we premiliary define an EditText so we externally specify...

2 minutes read.

Android 9.0 Pie vs. Android 10, which one is better

Android smartphone users are always searching for new system upgrades and keep an eye on system updates whenever the next version is published. Android 9 Pie and Android Q 10 are...

5 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.

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.

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 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.

Android Emulator

A tool for creating Android virtual devices (including software and virtual hardware) on your personal desktop is known as Emulator. We can use these virtual devices as the target device...

4 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.

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.

Dashboard UI Design in Android

One of the essential components that draw the user’s attentions into the application's operation is the dashboard design. It offers details on the application's general functionality in one location. Imagine...

11 minutes read.