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

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

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.

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.

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 Studio's Layout Editor

The Layout Editor allows you to efficiently create layouts by dragging UI elements from the Palette into the visual design editor instead of manually creating the layout XML file by...

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

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.

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

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

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

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 GridView

Theview group that displays items in a two-dimensional scrolling grid is called GridView. The data isadded into this grid layout from anArray List or database. The adapter class isutilized to...

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

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.