Android Broadcast Receiver

Android-Broadcast-Receiver.png

5th February, 2023

Broadcasts is a messaging system between apps in the Android operating system. Android Broadcast is a component in Android that allow the system and other apps to send and receive events.

1. What is Android Broadcast Receiver?

Android Broadcast receiver helps your app to register for events. You will be notified when those events occurred . For example, If you have registered your app for Airplane Mode changes, it will notify when the device gose into Airplane Mode.

Android-Broadcast-and-Receiver.png

In Android,
⇒ Intents are used to broadcast events to other apps.
⇒ To receive broadcast events you need to create a subclass of Android’s BroadcastReceiver class.
⇒ Avoid any long running task in the BroadcastReceiver.

2. Receiving Broadcasts

Below is the sample code of the Android Broadcast Receiver class.

content_copy light_mode remove
package com.androidchunk.broadcastreceivertest

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class MyReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        // This method is called 
        // when the BroadcastReceiver is receiving an Intent broadcast.
        Toast.makeText(context, "Intent detected!", Toast.LENGTH_SHORT).show()
    }
}
package com.androidchunk.broadcastreceivertest;

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

class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This method is called
        // when the BroadcastReceiver is receiving an Intent broadcast.
        Toast.makeText(context, "Intent detected!", Toast.LENGTH_SHORT).show();
    }
}

You can register a broadcast receiver in two ways.

2.1 Static Broadcast Receivers (Manifest declared receivers)

You can register Android Broadcast receiver by adding <receiver> tag to the androidmanifest.xml file. This method is known as Static Registering Android Broadcast Receivers.

From Android 8.0 or higher, You cannot use this method for most of implicit broadcasts.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
 
    <application
        ...
        ...
        ... >
 
        <!--
        android:enabled="true" ⇒ this application can be initiated by the system
 
        exported="true" ⇒ this application receives broadcasts from the system
                           and other apps
        -->
        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.AIRPLANE_MODE" />
            </intent-filter>
        </receiver>
 
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

2.1 Dynamic Broadcast Receivers (Context registered receivers)

Another way to register Android Broadcast is by using a context (like activity context, application context, etc). Create a subclass of Android’s BroadcastReceiver class and implement the onReceive() method. Register the Android Broadcast Receiver class by calling registerReceiver() method. This is know as Dynamic Broadcast Receivers or Context Registered Receivers.

content_copy light_mode remove
package com.androidchunk.broadcastreceivertest

import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    //create an object of BroadcastReceiver
    private var broadcastReceiver = MyReceiver()

    //create an object of IntentFilter
    private var intentFilter = IntentFilter(Intent.ACTION_REBOOT)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onStart() {
        super.onStart()
        //register broadcast receiver
        registerReceiver(broadcastReceiver, intentFilter)
    }

    override fun onDestroy() {
        super.onDestroy()
        //unregister broadcast receiver
        unregisterReceiver(broadcastReceiver)
    }
}
package com.androidchunk.broadcastreceivertest;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {

    //create an object of BroadcastReceiver
    private BroadcastReceiver broadcastReceiver = new MyReceiver();

    //create an object of IntentFilter
    private IntentFilter intentFilter = new IntentFilter(Intent.ACTION_REBOOT);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //register broadcast receiver
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //unregister broadcast receiver
        unregisterReceiver(broadcastReceiver);
    }
}

You can stop receiving broadcasts by calling the unregisterReceiver().

The point to note is that dynamic Broadcast receivers receives broadcasts as long as their context is alive. For example, If you registered your broadcast receiver using an Activity, the receiver receives broadcasts as long as the activity is alive.

Best practices for dynamically registering broadcast receivers in an Activity:
→ If you register broadcast receiver in onCreate(Bundle), Unregister the receiver in onDestroy().
→ If you register broadcast receiver in onResume(), Unregister the receiver in onPause().

3. Sending Broadcasts

In Android, You can send a broadcast in three ways:

Method Description
sendBroadcast(Intent) Send broadcasts to all receivers in asynchronous order
sendOrderedBroadcast(Intent, String) Send broadcasts to one receiver at a time
LoadBroadcastManager.sendBroadcast Send broadcast to receivers that are in the same app as the sender
content_copy light_mode remove
        //create object of Intent class
        val intent = Intent()
        //Add action
        intent.action = "actionXYZ"
        //data
        intent.putExtra("data", "Hello www.androidchunk.com")

        //send broadcast intent
        sendBroadcast(intent)
        //create object of Intent class
        Intent intent = new Intent();
        //Add action
        intent.setAction("actionXYZ");
        //data
        intent.putExtra("data","Hello www.androidchunk.com");

        //send broadcast intent
        sendBroadcast(intent);

4. Android System Broadcast

Android system automatically sends broadcasts when various events have occurred in the device. Some of them are given in the table below.

Event Description
android.intent.action.BATTERY_LOW It indicates low battery condition
android.intent.action.CONNECTIVITY_CHANGE It describes that connectivity of the device has changed
android.intent.action.POWER_CONNECTED When power connected to the device
android.intent.action.AIRPLANE_MODE It indicates that the airplane mode changed
android.intent.action.CALL_BUTTON This shows user pressed the call button
android.intent.action.DATE_CHANGED This broadcast trigger when Date of the device changed
android.intent.action.VIEW It displays data to the user
android.intent.action.MEDIA_MOUNTED It indicates media is present and mounted to its mount point
android.intent.action.REBOOT It means the device has rebooted

5. Implementation of custom Broadcast Receivers in Android

Android allow us to create custom broadcasts. Let’s see how to send and receive custom broadcasts one by one.

Sending custom broadcast

Create an instance of the Intent class and add your string as the intent action. Send it using the sendBroadcast(intent) method.

content_copy light_mode remove
        //create object of Intent class
        val intent = Intent()
        //Add action
        intent.action = "com.androidchunk.broadcastreceivertest.CUSTOM_INTENT"
        //data
        intent.putExtra("data", "Hello www.androidchunk.com")

        //send broadcast intent
        sendBroadcast(intent)
        //create object of Intent class
        Intent intent = new Intent();
        //Add action
        intent.setAction("com.androidchunk.broadcastreceivertest.CUSTOM_INTENT");
        //data
        intent.putExtra("data","Hello www.androidchunk.com");

        //send broadcast intent
        sendBroadcast(intent);

Receiving custom broadcast

To receive a custom broadcast, declare an action in the manifest file. See sample code.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
  
    <application
        ...
        ...
        ... >
        <receiver
            android:name=".MyReceiver">
            <intent-filter>
                <action android:name="com.androidchunk.broadcastreceivertest.CUSTOM_INTENT" />
            </intent-filter>
        </receiver>
  
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
  
</manifest>
        //create object of Intent class
        Intent intent = new Intent();
        //Add action
        intent.setAction("actionXYZ");
        //data
        intent.putExtra("data","Hello www.androidchunk.com");

        //send broadcast intent
        sendBroadcast(intent);

Happy coding!

Leave a Reply