NAVIGATION - SEARCH

Android - How To Send and Receive Broadcasts AKA Broadcast Receivers

A broadcast receiver enables your app to send or receive a message to another application or part of your application to inform of some events. These messages are sometime called events or intents. For e.g. you may register a broadcast receiver which when broadcast informs the app the start a service and download some content or you may register a receiver which simply gets a message whenever your device is rebooted. In simpler terms, a broadcast receiver is used to intercept some communication and initiate some action.

You can create a broadcast receiver in two ways, programatically through code or declaring via the AndroidManifest.xml file

Registering Broadcast Receiver - Programatically

package com.youritbuddy.demo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity 
{
	TestBroadcastReceiver receiver;
	IntentFilter intent;
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		receiver = new TestBroadcastReceiver();
		intent = new IntentFilter("SOME_ACTION");
	}

	@Override
	public void onResume() 
	{
		super.onResume();
		
		registerReceiver(receiver, intent);
	}

	@Override
	public void onPause() 
	{
		super.onPause();
		
		unregisterReceiver(receiver);
	}

	public void onClick(View view) 
	{
		Intent i = new Intent("SOME_ACTION");
		i.putExtra("somedata", "some data send to broadcast receiver");
		sendBroadcast(i);
	}
	
	public class TestBroadcastReceiver extends BroadcastReceiver 
	{
		@Override
		public void onReceive(Context context, Intent i) 
		{
			Toast.makeText(context, "Received broadcast message = " + i.getStringExtra("somedata"), Toast.LENGTH_LONG).show();
		}
	}
}

The above code snippet shows the class TestBroadcastReceiver extending from the BroadcastReceiver base class. In this class, the onReceive() method is overridden so that when the broadcast is received, some action is performed. If some data is passed to the receiver, then Intent object can be used to retrieve data inside the broadcast receiver which is the second argument of the onReceive() method.

This broadcast receiver will only work if "SOME_ACTION" intent filer is passed even if sent by another application. This broadcast receiver will not work if the application is in background since we have unregistered the broadcast receiver inside onPause() method.

For a more persistent way to receive broadcasts, register the BroadcastReceiver class inside the AndroidManifest.xml file. After that create the BroadcastReceiver class in another Java class.

package com.youritbuddy.demo;

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

public class TestBroadcastReceiver extends BroadcastReceiver 
{
	@Override
	public void onReceive(Context context, Intent i) 
	{
		String ACTION = i.getAction();
		
		//IF MULTIPLE BROADCASTS REGISTERED THEN USE IF CONDITION TO HANDLE SPECIFIC REQUESTS
		
		if (ACTION.equalsIgnoreCase("SOME_ACTION"))
			Toast.makeText(context, "Received broadcast message = " + i.getStringExtra("somedata"), Toast.LENGTH_LONG).show();
	}
}

To register this receiver in the AndroidManifest.xml file, add the following element:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.youritbuddy.demo"
	android:versionCode="1"
	android:versionName="1.0" >
	
	<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="21" />
	
	<application
		android:icon="@drawable/ic_launcher"
		android:label="@string/app_name"
		android:theme="@style/AppTheme" >
		<activity
			android:name=".MainActivity"
			android:label="@string/appTitle" >
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		
		<receiver android:name=".TestBroadcastReceiver" >
			<intent-filter>
				<action android:name="SOME_ACTION" />
			</intent-filter>
		</receiver>
	</application>
</manifest>

This method will be able to process broadcast message even if the application is not open or active. There are various system level broadcast messages which can be used inside your app. Some of the important ones are listed below.

android.intent.action.BATTERY_CHANGED - Sticky broadcast containing the charging state, level, and other information about the battery.

android.intent.action.BATTERY_LOW - Indicates low battery condition on the device.

android.intent.action.BATTERY_OKAY - Indicates the battery is now okay after being low.

android.intent.action.BOOT_COMPLETED - This is broadcast once, after the system has finished booting.

android.intent.action.BUG_REPORT - Show activity for reporting a bug.

android.intent.action.CALL - Perform a call to someone specified by the data.

android.intent.action.CALL_BUTTON - The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.

android.intent.action.DATE_CHANGED - The date has changed.

android.intent.action.REBOOT - Have the device reboot.

A combination of above broadcast messages can be very helpful in developing real world applications. For e.g. if your app listens to periodic location updates then you can use BOOT_COMPLETED broadcast to restart location updates in case the user has rebooted the device or if your app is dependent on system time then you can take appropriate action in case user changes the device date using the DATE_CHANGED broadcast.

Add comment