Free Android app covering all aspects of addiction, including prevention and treatment

Android Broadcast Receivers: A Tutorial

  • Written by  Clive

Here’s how to use Broadcast Receivers in your apps: A Tutorial

Broadcast receivers tutorial icon

What you’ll learn

This tutorial will show you how to:

  • Register a Broadcast Receiver in your app’s manifest file. We’ll use this receiver to receive a System broadcast sent when the power cable is plugged into the device
  • Register a Broadcast Receiver in an activity. We’ll use this one to show you how to use permissions to secure your broadcasts and the receiver. This receiver will only receive broadcast intents that have the required permission
  • Use the LocalBroadcastManager to send and receive a local broadcast. A secure way of using broadcasts within your app

Android BroadcastReceivers Diagram

A diagrammatic representation of our BroadcastReceiver tutorial app

You may want to read the article, Android Broadcast Receivers if you haven't already done so. It covers the basics of Broadcast Receivers.

Where it starts: The MainActivity activity

It all starts with the main activity. The main activity displays two buttons:

  • One starts the SecondActivity activity
  • One starts the ThirdActivity activity

Android Broadcast Receivers screenshot main activity

Plugging in the power plug will start the main activity

There are three ways in which the main activity can be started:

  • it starts when the app starts
  • It starts when the power/Usb cable is plugged into the device
  • It’s started by the Service when it has finished its work

When the main activity is started by the Service, it displays a message in the LogCat. You can read more about the LogCat in Using Android’s Log class API to debug Android application code.

The message differs depending on which broadcast started the service.

Follow along in the log

Here’s a printout of the log:

Broadcast Receivers logcat

You can follow the logic of the app in the logcat

Here’s the code for getting the message string out of the intent that started the main activity:

Broadcast Receiver getMessage

Get the message out of the intent and display it in the logcat

Note the following:

  • message – if the activity is started by an intent, then we get the message string out of the intent and assign its value to our String, message. We use an if statement to check if there is a message string, in which case we display it in the logcat

Here’s the code for the Start Permission Broadcast button. Pressing it starts the ThirdActivity activity:

Broadcast Receiver start third activity

We use an intent to start the third activity

Note the following:

  • intent – we use an intent to start the activity. We pass it two parameters:
    • the context
    • the name of the activity that we want to start
  • startActivity – starts the activity specified in the intent passed as a parameter

The code for the Start Local Broadcast button is the same.

The Great Receiver: MyBroadcastReceiver

We’ll use a broadcast receiver to listen for a Native Android Action. These are the Standard Android Broadcast Actions. The specific one we’re listening for is the ACTION_POWER_CONNECTED action.

This Broadcast Action indicates that the device has been connected to a power source. Our receiver will listen for this broadcast, even if the app is not running.

We create a Broadcast Receiver, MyBroadcastReceiver:

Broadcast Receiver myBroadcastReceiver

Our broadcast receiver has one method, the onReceive method that executes when a matching broadcast intent is received

Note the following:

  • onReceive – it’s executed on the main application thread when a matching broadcast intent is received. It must complete within 5 seconds else an Application Not Responding dialog will display
  • intentStartMainActivity – this is our intent that we use to start the main activity. It has two parameters:
    • the context – we use onReceive’s  context
    • the activity that we want to start
  • setFlags – we need to set the flag to FLAG_ACTIVITY_NEW_TASK because we are starting the activity from outside an activity context
  • context.startActivity – we use the onReceive methods context to call startActivity(), passing it the intent that specifies which activity to start

Once the power cable is plugged in, the system broadcasts this event. The receiver’s onReceive method is executed and the main activity is started.

We’re going to register the receiver in the manifest so that it will receive broadcasts even if the app is not running.

Declare your stuff: Register the Broadcast Receiver in the AndroidManifest.xml file

We need to register the receiver in the manifest file:

Broadcast Receiver myBroadcastReceiver Manifest

This receiver is known as a manifest receiver because it is registered in the AndroidManifest.xml file. It will receive broadcasts even if the app is not running

Note the following:

  • name – the class name of the receiver
  • <intent-filter> - this filter specifies which intents our receiver will respond to
  • action – this attribute must be included in the filter. It tells the receiver which event to listen out for. The event is an action that has taken place and has been broadcast (in our case, the power has been connected)
  • name – the name of the action. We’re using a standard action, ACTION_POWER_CONNECTED with a given format. You can see more Standard Broadcast Actions in the documentation
  • this receiver will receive the matching broadcast intent even if the app is not running

Broadcasting with permission: The SecondActivity activity

The second activity displays a button. Pressing the button broadcasts an intent that includes a required permission.

We also register a receiver in the activity. The receiver includes the required permission. It will only receive broadcasts that have this permission.

Broadcast Receiver screenshot 2nd activity

Pressing the button broadcasts an intent that includes a required permission

We create a number of fields in the activity:

Broadcast Receiver secondActivity constants

We declare an action constant and a required permission constant

Note the following:

  • ACTION_PERMISSION_TEST – this is our custom broadcast intent action. Good practice is to use your package name followed by your custom action
  • requiredPermission – this is our custom permission that will be used by the broadcast intent and the receiver. Again we use our package name followed by our custom permission
  • filter – our intent filter
  • receiver – our receiver

Then we create our receiver and filter objects:

Broadcast Receiver secondActivity new fields

We create our receiver and intent filter, which includes the action constant

Note the following:

  • receiver – we create a new PermissionReceiver object. See the below for more on the PermissionReceiver
  • filter – we create our new filter, specifying our custom action as the parameter

Next, we send the broadcast with this code which is executed when the button is pressed:

Broadcast Receiver secondActivity sendBroadcast

We broadcast the intent which includes the required permission

Note the following:

  • intentBroadcastPermission – our broadcast intent. We pass the action as a parameter. This will be matched with the receiver’s filter
  • sendBroadcast – sends the broadcast. We pass two parameters:
    • the broadcast intent
    • the required permission. This will be matched with the receiver’s required permission

Register your receiver dynamically in code

We register and unregister our receiver in the activity’s code.

Usually you would register receivers in the activity if they affect its User Interface. These receivers are only active while the activity is running.

Broadcast Receiver secondActivity unregister

We register the receiver in the activity’s onResume method and unregister it in the onPause method

Receiving with permission: The PermissionReceiver

We create our receiver class, PermissionReceiver by extending the BroadcastReceiver class.

Our PermissionReceiver receives any broadcast that has an intent that matches its filter and also includes the required permission.

Here’s our receiver’s onReceive method:

Broadcast Receiver permissionOnReceiver

The PermissionReceiver’s onReceive method executes its code when it receives a matching broadcast intent which includes the required permission

Note the following:

  • intentStartPermissionService – our intent that we use to start the Service. It receives two parameters:
    • the context – we use onReceive’s context
    • the Service that we want to start
  • putExtra – we add an int value to the intent using the constant KEY_SERVICE_TYPE as the key and 3 as the value. We’ll use this value in the ForthActivity activity to identify which broadcast intent started the Service
  • context.startService – we start the Service, using onReceive’s context. We pass the intent as a parameter

Declare the permission in the manifest

Although we register this receiver in code, we still have to declare the required permission in the app’s manifest file:

Broadcast Receiver permissions manifest

We declare the required permission in the app’s AndroidManifest.xml file

Doing the work in the background: The Service

The Service is started in:

  • myLocalReceiver’s onReceive method (in the ThirdActivity activity)
  • the PermissionReceiver’s onReceive method

Once these receivers have received their broadcast intents, they start the Service. The Service starts a separate thread to do some work. When it’s finished, it starts the ForthActivity activity.

Have a look at the article, All about Services for more on Services. It includes links to a number of Service’s tutorials. You may also be interested in the article on threads, Processes and Threads.

Wrapping it up: The ForthActivity activity

The forth activity does not have a User Interface.

It is started by the Service when it has finished its work. It stops the Service and starts the main activity, passing it an appropriate message.

The Service passes the KEY_SERVICE_TYPE value as an intent extra. This indicates which broadcast receiver started the Service.

We get the KEY_SERVICE_TYPE value out of the intent and assign it to our serviceType variable:

Broadcast receiver serviceType

Get the KEY_SERVICE_TYPE extra out of the intent that started the ForthActivity activity

You may want to have a look at the tutorial, Passing data between activities for more on including data in intents.

We use a switch statement to filter the serviceType value. The code in the matching case statement is then executed. Here are the possibilities:

  • -1 – there’s an error as no KEY_SERVICE_TYPE value was received. The -1 default was used
  • 0 – not used
  • 1 – not used
  • 2 – received from the myLocalReceiver’s onReceive method in the third activity
  • 3 – received from the PermissionReceiver’s onReceive method

Here’s the code for case 2:

Broadcast Receiver stop service

We create an intent that we use to stop the Service

Note the following:

  • stopLocalService – our intent that we’ll use to stop the Service. It receives two parameters:
    • the context
    • the Service that we want to stop
  • stopService – our call to stop the Service. We pass our intent as a parameter. It specifies which service to stop
  • message – the message that we’ll pass as an extra in the intent that we will use later to start the main activity

Once the switch statement has finished, we start the main activity:

Broadcast Receiver start MainActivity

Start the main activity and pass the appropriate message as an extra

Note the following:

  • startMainActivityIntent – our intent that we use to start the main activity. It has two parameters:
    • the context
    • the activity that we want to start
  • putExtra – we include the message in the intent as an extra
  • startActivity – starts the activity specified in the intent that we pass as a parameter

Keeping it local: The ThirdActivity

The third activity displays a button. Pressing the button broadcasts a local broadcast.

We also register a broadcast receiver in this activity to receive the broadcast.

Broadcast receiver screenshot 3rd activity

Pressing the button sends a local broadcast intent

We create two constants:

Broadcast Receiver third activity fields

We use the KEY_SERVICE_TYPE constant in the intent used to start the Service and ACTION_LOCAL_BROADCAST as the broadcast intent’s action

The LocalBroadcastManager

We register the receiver in the activity’s onCreate method:

Broadcast Receiver third activity register Receiver

Register the local broadcast’s receiver in the activity’s onCreate() method

Note the following:

  • getInstance – gets an instance of the local broadcast manager
  • registerReceiver – registers our local broadcast receiver. It receives two parameters:
    • our receiver
    • an intent filter
  • IntentFilter – the intent filter with our action parameter. Broadcast intents need to have a matching action for this receiver to receive their broadcasts

Pressing the button sends the broadcast. Here’s the code:

Broadcast receiver third activity sendBroadcast

Create your broadcast intent, include the action, then use an instance of the local broadcast manager to send the broadcast when the button is pressed

Note the following:

  • Intent – our broadcast intent which includes the intent action as a parameter
  • putExtra – we put the message in the intent as an extra.  This message will be displayed in the logcat by the receiver when it processes the broadcast intent
  • getInstance - gets an instance of the local broadcast manager. We pass the context as a parameter
  • sendBroadcast – broadcasts the intent passed as a parameter

Is it local? The local receiver

This receiver will receive any broadcast with a matching intent action, including broadcasts from other apps.

Here’s the code for our inner class receiver:

Broadcast Receiver third activity onReceive

Our local broadcast receiver’s onReceive method starts the Service to do the work in a separate thread

Note the following:

  • getStringExtra – we get the message string out of the intent
  • intentStartService – the intent that we’ll use to start the Service. It receives two parameters:
    • the context
    • the Service that we want to start
  • putExtra – we put the KEY_SERVICE_TYPE value of 2 into the intent. This will eventually be used by the ForthActivity activity’s switch statement to determine which broadcast started the Service
  • context.startService – we start the Service identified in the intent that we pass as a parameter. We use onReceive’s context

We unregister the receiver in the activity’s onDestroy method:

Broadcast Receiver third activity unregister

Unregister the receiver in the activity’s onDestroy() method

Note the following:

  • getInstance - gets an instance of the local broadcast manager. We pass the context as a parameter
  • unregisterReceiver – unregisters the receiver. We pass the receiver that we want to unregister as the parameter

I hope that you have found this tutorial helpful.

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.