What are Broadcasts?

Consider a situation in which you are downloading a large file in your app and suddenly the battery goes critically low , you don’t want the download to stop abruptly and would like to show the user a notification/dialog so that he can pause the download. Creating a service just to keep on checking the battery power would be too much work for a simple notification. What if the android system itself notifies you of any such system event like battery low or airplane mode.

Guess what? It does!. And you can handle these events very efficiently.. These events are known as broadcasts and you need to handle them in a broadcast receiver. Your app can have its own custom broadcasts which it can send within the app or to other apps on the device to notify them of an event they might be interested in.

One common use case of sending broadcasts within the same app is mentioned here:

Suppose you have updated your profile details in an activity inside the app, you would like the updated changes to be reflected immediately in all the other active activities without having to refresh them. In this case you can send a broadcast informing the other activities that the profile details are updated

Basically there are two types of Broadcasts:

System Broadcasts these are the broadcasts which the Android system sends to notify the apps of some events like Battery low, Airplane mode etc

Custom broadcasts These are the broadcasts which are defined by apps and sent to notify others of any event

What is a Broadcast Receiver ?

Here is the standard definition of Broadcast Receiver

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.

So broadcast receivers are created in order to receive and handle broadcasts sent by either the system or the any other app. To receive any broadcast the receiver has to subscribe for that particular event. Once registered the receiver will be notified whenever that broadcast is sent. This complete concept will be more clear with am example given below

Note: Each receiver can subscribe to multiple broadcasts and will be triggered if any of those are sent

Step 1 Creating a broadcast

Creating the receiver is very simple. You just need to create a class which extends the BroadcastReceiver abstract class and implement the onReceive method.This method is triggered when the receiver receives a broadcast. You also have an Intent object and Context passed as parameters in the the onReceive callback. You can use the Intent to get any additional information passed along with the broadcast

public class MyBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { } }

Step-2 Register the Broadcast Receiver :

This is perhaps the most important step in creating your broadcast receiver. This is where you subscribe to the events(broadcasts) the receiver will be listening to.There are two ways of doing this

Registering in the manifest:

Broadcast receiver can be declared in the manifest files similar to the other components like activity, service etc . You will have to subscribe to the broadcast by mentioning them under the intent filter tag as shown in the code snippet belowThis kind of declaration makes this receiver a new entry point in the app. Which means that this receiver will be invoked whenever the broadcast is sent regardless of whether the app is running or not. In short this broadcast will always be active <receiver android:name=".MyBroadcast"> <intent-filter> <action android:name="<Mention- the -broadcast- you- will-be-listening-to>"/> </intent-filter> </receiver>

Broadcast receiver can be declared in the manifest files similar to the other components like activity, service etc . You will have to subscribe to the broadcast by mentioning them under the intent filter tag as shown in the code snippet belowThis kind of declaration makes this receiver a new entry point in the app. Which means that this receiver will be invoked whenever the broadcast is sent regardless of whether the app is running or not. In short this broadcast will always be active Registering with context.

Broadcast Receiver can also be declared dynamically in code with the help of context. Such kind of declarations are very useful if you want to receive broadcast from within your app .This receiver will be active only as long as the context is active. That means if you have declared this receiver in an activity it will no longer receive broadcasts once the activity is killed. Code snippet below explains how you can register a receiver dynamically in code. MyBroadcastReceiver broadCastReceiver=new MyBroadcastReceiver(); context.registerReceiver(broadCastReceiver,new IntentFilter("android.intent.action.TIME_TICK"); If you are using a dynamically registered receiver you will have to unregister it. For example if you have registered your Receiver in onCreate don’t forget to unregister it in onDestroy since after that the context will be inactive public void onDestroy() { super.onDestroy(); context.unregisterReceiver(broadCastReceiver); }

Example

In this example we will create a receiver which will listen to the AIRPLANE_MODE system broadcast. That means every time the airplane mode is switched on/off android will fire this broadcast and our receiver will be notified.

We will first create a custom receiver class which will extend the BroadcastReceiver abstract class. Our class will have to implement the onReceive method. public class AirplaneBroadcast extends BroadcastReceiver { /* This method will be invoked when any of the subscribed broadcasts are fired. We can check which broadcast was fired by using intent.getAction() This will be usefull if the same receiver is listening to multiple broadcasts */ @Override public void onReceive(Context context, Intent intent) { //We are checking which broadcast was actually fired if (intent.getAction()==Intent.ACTION_AIRPLANE_MODE_CHANGED){ Toast.makeText(context,"Airplace MOdeChanged",Toast.LENGTH_SHORT).show(); } } }

Once the you have created your custom receiver you should now register the it.In this example we will register it in the menifest. Meaning it will always listen for that event even if the app is killed. Copy the cope snippet below in your AndroidManifest.xml. You can see how we have specified AIRPLANE_MODE broadcaast in the <intent-filter> tag. This will register our receiver to listen for Airplance mode change events. <receiver android:name=".utils.AirplaneBroadcast"> <intent-filter> <action android:name="android.intent.action.AIRPLANE_MODE"/> </intent-filter> </receiver>

Conclusion :

You can now run this app on your device and notice that you see a Toast message whenever Airplane Mode is switch on/off. You will see this Toast message even if your app is killed . This means your receiver is working