Broadcast Receiver in Android With Example

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers allow us to register for the system and application events, and when that event happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers:

Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so we have implemented dynamic receivers in our sample project given below. There are some static fields defined in the Intent class which can be used to broadcast different events. We have taken a change of airplane mode as a broadcast event, but there are many events for which broadcast register can be used. Following are some of the important system-wide generated intents:-

Description Of Event

The two main things that we have to do in order to use the broadcast receiver in our application are:

Creating the Broadcast Receiver:

class AirplaneModeChangeReceiver:BroadcastReceiver()

override fun onReceive(context: Context?, intent: Intent?)

// logic of the code needs to be written here

>

>

Registering a BroadcastReceiver:

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also

// receiver is the broadcast receiver that we have registered

// and it is the intent filter that we have created

registerReceiver(receiver,it)

>

Example

Below is the sample project showing how to create the broadcast Receiver and how to register them for a particular event and how to use them in the application.

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.