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

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

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.

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.

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.

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.

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

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

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

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