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 Time picker example

How to pick Time from the user in android? Write an android example to pick Time from the user and display the date to the user. Android provides controls for the user...

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

Event Handling in Android

Events are a convenient way to gather data about user interactions with interactive elements of your application. Like a button click or a screen touch. A queue of events on...

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

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.

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

Android Studio Resources

To build an outstanding Android application there are many items that you need to use. Aside from the coding of your application, you need to handle various resources such as...

5 minutes read.

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.

How to Update Gradle in Android Studio?

The Android Gradle plugin adds a number of features that are unique to develop Android apps to the Gradle build system, which is the foundation of the Android Studio development...

2 minutes read.