Broadcast Receiver

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


Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.


For example, applications can register for the ACTION_BOOT_COMPLETED system event which is fired once the Android system has completed the boot process.


Unlike activities, android Broadcast Receiver doesn't contain any user interface. Broadcast receiver is generally implemented to delegate the tasks to services depending on the type of intent data that's received.
Following are some of the important system wide generated intents.

Constant Description
android.intent.action.BATTERY_LOW Indicates low battery condition on the device.
android.intent.action.BOOT_COMPLETED This is broadcast once, after the system has finished booting
android.intent.action.CALL To perform a call to someone specified by the data
android.intent.action.DATE_CHANGED The date has changed
android.intent.action.REBOOT Have the device reboot
android.net.conn.CONNECTIVITY_CHANGE The mobile network or wifi connection is changed(or reset)

We will discuss here-

  • Creating the Broadcast Receiver.
  • Registering Broadcast Receiver

Creating a BroadcastReceiver

A broadcast receiver is implemented as a subclass of Broadcast Receiver class and overriding the onReceive() method where each message is received as a Intent object parameter.

Example:
package com.theitbulls.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent == null) {
            Log.d("NoIntent:", "Intent is empty or null");
            return;
        }

        if(intent.getAction().equals(MainActivity.INTENT_FILTER_ACTION)) {
            // TODO your task
            Toast.makeText(context, "Invoked: " + intent.getAction(), Toast.LENGTH_SHORT).show();
        }
    }
}

The onReceiver() method is first called on the registered Broadcast Receivers when any event occurs.

The intent object is passed with all the additional data. A Context object is also available and is used to start an activity or service using context.startActivity(myIntent); or context.startService(myService); respectively.


Registering Broadcast Receiver

An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. Consider we are going to register MyReceiver.

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theitbulls.broadcastreceiverdemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <receiver android:name=".MyReceiver"/>
    </application>
</manifest>


Note: To make the broadcast receiver unavailable to external applications, add the attribute android:exported=false in the manifest. When we send a broadcast, it is possible for the external applications too to receive them.


System Broadcast Receiver Example
package com.theitbulls.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class BatteryLowReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent == null) {
            Log.d("NoIntent:", "Intent is empty or null");
            return;
        }

        if(intent.getAction().equals("android.intent.action.BATTERY_LOW")) {
            // TODO your task
            Toast.makeText(context, "Battery Low: " + intent.getAction(), Toast.LENGTH_SHORT).show();
        }
    }
}

Add Receiver into AndroidManifest.xml
<receiver android:name=".BatteryLowReceiver">
     <intent-filter>
          <action android:name="android.intent.action.BATTERY_LOW"/>
     </intent-filter>
</receiver>

Download Complete example

Download: BroadcastReceiverDemo.zip