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 example, the Android OS sends broadcasts when a variety of system events happen, such as when the devicerestarts or the device goes into airplane mode. Applications can also send personalized broadcasts, for example, to notify other applications of something that they might interact with.

Some use cases of the Broadcast Receiver are:

1. Communication between multiple apps

2. Create Bound Services within the Applications

3. Respond to system events that occur within the device

A BroadcastReceiver is an Android Class that receives these broadcasts and performs services accordingly.

Broadcast Receiversare divided into 2 types as follows:

  • Static Broadcast Receivers: Static broadcastreceivers also known as manifest-declared receivers are specified in the android manifest file and works even if the application is shut down.
  • Dynamic Broadcast Receivers: Dynamic broadcast receivers work only if the application is working or minimized.

Static Broadcast Receivers

1. Declare the element in your application's manifest.

<receiver android:name=".ExampleBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" /
>
</intent-filter>
</receiver>

2. Create a BroadcastReceiver’s subclass

public class ExampleBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "ExampleBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
StringBuilder str= new StringBuilder();
str.append("Action: " + intent.getAction() + "\n");
str.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");
String log = str.toString();
        Log.d(TAG, log);
        Toast.makeText(context,log,Toast.LENGTH_SHORT).show();
    }
}

Dynamic Broadcast Receivers

1. Create a Receiver’s instance

BroadcastReceiver Newbr = new MyBroadcastReceiver();

2. Create and add intent-filters for the Receivers

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(Newbr, filter);

Sending a Broadcast

To send a broadcast, add the following code to your activity class file

Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data", "Life goes on.");
sendBroadcast(intent);

Most of the broadcast can only be received by the dynamic receivers since API level 21, so we have implemented dynamic receivers in our project example given below. Some static fields are defined in the Intent class, which can be utilized to broadcastvarious events. We consider the flight mode change as a broadcast event, but the broadcast log can be used for many events.

Some of the system-wide generated intents are-

    IntentDescription Of Event
android.intent.action.BATTERY_LOW :Shows low battery notification on the device.
android.intent.action.BOOT_COMPLETEDShows that the system has completed booting
android.intent.action.CALLTo make a call to someone mentioned by the data
android.intent.action.DATE_CHANGED Shows that the date has altered
android.intent.action.REBOOTShows that the device has gone into reboot
android.net.conn.CONNECTIVITY_CHANGEThe mobile network or Wi-Fi connection is altered (or reset)
android.intent.ACTION_AIRPLANE_MODE_CHANGEDThis shows that airplane mode has been switched on or off.

Example

Below is an example project showing how to make the broadcast Receiver and how to register and utilizethem for a specific event in the android application.

1) Create a New Project

Create a new android project in Android Studio. If you come across any problem in creating a new project, please refer to Android Studio Tutorial.

2) Modifying the activity_main.xml file

Open the activity_main.xml file and the code for the activity_main.xml file will be as follows:

<?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:background="#FFEB3B"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

3) Modifying the MainActivity.java file

Go to the MainActivity java file and make the following changes as mentioned in the following code:

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


public class MainActivity extends AppCompatActivity {


    AirplaneModeSwitchReceiver airplaneModeSwitchReceiver = new AirplaneModeSwitchReceiver();


@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(airplaneModeSwitchReceiver, filter);
    }


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

4) Make airplaneModeSwitchReceiverclass

Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Class file and name the files as AirplaneModeSwitchReceiver. Below is the code for the AirplaneModeSwitchReceiver file.

import android.widget.Toast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;


public class AirplaneModeSwitchReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
if(checkAirplaneMode(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 checkAirplaneMode(Context context){
return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}
Broadcast Receivers

Related Topics

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.

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

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.

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.

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.

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 to insert the image...

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

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.

Top 7 Android App Development Books

Do you want to create Android apps but don't know where to start? One should first be familiar with the basics of Android before we discuss these books. With 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.

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.

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.

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

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.

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.

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.

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