Android BroadcastReceiver tutorial Android 10.03.2017

A Broadcast Receiver (part of the android.content package) is a publish-and-subscribe system that is based on an Intent. In a sense, the purpose of an Android BroadcastReceiver is to "listen" to Android Intents.


Broadcast receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task. Unlike activities, a BroadcastReceiver doesn’t contain any user interface. It’s generally implemented to do minimal amount of work, for example, 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.

  • 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.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.
  • : The mobile network or wifi connection is changed(or reset)

Life cycle of a broadcast receiver is very simple: after the onReceive() of the receiver class has finished, the Android system is allowed to recycle the receiver. A BroadcastReceiver which is on the manifest is always active and it works even if the activity is no longer running. Receivers which are defined and registered dinamically only work when the app is running (such as LocalBroadcastManager).

Android BroadcastReceiver tutorial

Every intent you send as a broadcast must have an action name. Although the action name can be any string, I recommend that you always prefix it with the package name of your app in order to avoid conflicts with broadcasts of other applications.

The follow code snippet shows you how to create a new intent whose action name is me.proft.helloworld.broadcast

Intent i = new Intent("me.proft.helloworld.broadcast");
// i.putExtra("name", "value");

To send the intent as a broadcast, all you need to do is call the sendBroadcast() method and pass the Intent object as an argument to it.


Note that the sendBroadcast() method creates a global broadcast that can be received by not only your application but also any other application installed on the user's device.

There are several types of Broadcast: Local, Normal, Ordered and Sticky.

Normal Broadcast

  • use sendBroadcast()
  • asynchronous broadcast
  • any receiver receives broadcast not any particular order

Ordered Broadcast

  • use sendOrderedBroadcast()
  • synchronous broadcast
  • receiver receives broadcast in priority base
  • we can also simply abort broadcast in this type

Local Broadcast

  • use only when broadcast is used only inside same process

Sticky Broadcast

  • normal broadcast intent is not available any more after is was send and processed by the system
  • use sendStickyBroadcast(Intent)
  • the corresponding intent is sticky, meaning the intent you are sending stays around after the broadcast is complete
  • because of this others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)
  • apart from this same as sendBroadcast(Intent)

To set up a broadcast receiver in our android application we need to do the following two things.

  • Creating a BroadcastReceiver
  • Registering a BroadcastReceiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter. Let’s quickly create a custom BroadcastReceiver as shown below:

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {}

    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();

BroadcastReceiver is an abstract class with the onReceiver() method being abstract. 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.

A BroadcastReceiver can be registered in two ways.

By defining it in the AndroidManifest.xml file as shown below.

<receiver android:name=".MyReceiver">
        <action android:name="" />

Using intent filters we tell the system any intent that matches our subelements should get delivered to that specific broadcast receiver.

By defining it programmatically.

IntentFilter filter = new IntentFilter();
filter.addAction(getPackageName() + "");

MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);

To unregister a receiver in onStop() or onPause() of the activity the following snippet can be used.

protected void onPause() {

If you want your application itself should generate and send custom intents then you will have to create and send those intents by using the sendBroadcast() method inside your activity class. The following snippet is used to send an intent to all the related broadcast receivers.

Intent intent = new Intent();

Don’t forget to add the above action in the intent-filter tag of the manifest or programmatically.

Broadcast intents

Broadcast intents are Intent objects that are broadcast via a call to the sendBroadcast(), sendStickyBroadcast() or sendOrderedBroadcast() methods of the Activity class (the latter being used when results are required from the broadcast). In addition to providing a messaging and event system between application components, broadcast intents are also used by the Android system to notify interested applications about key system events (such as the external power supply or headphones being connected or disconnected).

When a broadcast intent is created, it must include an action string in addition to optional data and a category string. As with standard intents, data is added to a broadcast intent using key-value pairs in conjunction with the putExtra() method of the intent object. The optional category string may be assigned to a broadcast intent via a call to the addCategory() method.

The action string, which identifies the broadcast event, must be unique and typically uses the application’s package name syntax. For example, the following code fragment creates and sends a broadcast intent including a unique action string and data:

Intent intent = new Intent();
intent.putExtra("MyData", 1000);

The above code would successfully launch the corresponding broadcast receiver on a device running an Android version earlier than 3.0. On more recent versions of Android, however, the intent would not be received by the broadcast receiver. This is because Android 3.0 introduced a launch control security measure that prevents components of stopped applications from being launched via an intent. An application is considered to be in a stopped state if the application has either just been installed and not previously launched, or been manually stopped by the user using the application manager on the device. To get around this, however, a flag can be added to the intent before it is sent to indicate that the intent is to be allowed to start a component of a stopped application. This flag is FLAG_INCLUDE_STOPPED_PACKAGES and would be used as outlined in the following adaptation of the previous code fragment:

Intent intent = new Intent();
intent.putExtra("MyData", 1000);

When running on versions of Android older than Android 8.0, the intent filters associated with a receiver can be placed within the receiver element of the manifest file as follows:

<receiver android:name="MyReceiver">
        <action android:name="com.example.Broadcast"></action>

On Android 8.0 or later, the receiver must be registered in code using the registerReceiver() method of the Activity class together with an appropriately configured IntentFilter object:

IntentFilter filter = new IntentFilter("com.example.Broadcast");
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, filter)

Sending broadcast from adb command line tool

You can use the following command from the adb command line tool. The class name and package names which are targeted via the command line tool need to be as defined in the manifest. You should send the intent you generated to your specific component, for example if you send a general ACTION_BOOT_COMPLETED broadcast, this will trigger a lot of things in an Android system.

# trigger a broadcast and deliver it to a component
adb shell am activity/service/broadcast -a ACTION -c CATEGORY -n NAME

# for example send to specific package (this goes into one line)

adb shell am broadcast -a
android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n

# for example send to all packages
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

Example of BroadcastReceiver

Let’s develop an application that listens to network change events and also to a custom intent and handles the data accordingly.

The activity_main.xml consists of a button at the center that sends a broadcast intent.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

        android:text="Send broadcast"
        android:onClick="sendTestBroadcast" />

The is given below.

public class MainActivity extends AppCompatActivity {
    ConnectionReceiver receiver;
    IntentFilter intentFilter;

    protected void onCreate(Bundle savedInstanceState) {

        receiver = new ConnectionReceiver();
        intentFilter = new IntentFilter("me.proft.helloworld.broadcast");

    protected void onResume() {
        registerReceiver(receiver, intentFilter);

    protected void onDestroy() {

    void sendTestBroadcast(View v) {
        Intent intent = new Intent("me.proft.helloworld.broadcast");
        intent.putExtra("Foo", "Bar");

In the above code we’ve registered another custom action programmatically. The ConnectionReceiver is defined in the AndroidManifest.xml file as below:

    <receiver android:name=".ConnectionReceiver">
            <action android:name="" />

The class is defined below.

public class ConnectionReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Log.d("TAG", "" + intent.getAction());

            Toast.makeText(context, "HELLOWORLD is received", Toast.LENGTH_LONG).show();
        else {
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&

            if (isConnected) {
                try {
                    Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
            } else {
                Toast.makeText(context, "Network is changed or reconnected", Toast.LENGTH_LONG).show();

Example of LocalBroadcastManager

The LocalBroadcastManager class is a helper class to register local broadcast receivers as well as send broadcasts of intents to them within our own app’s process rather than sending global broadcasts using sendBroadcast() as we saw before. It is more efficient as well as secured compared to global broadcasts through the system as the data won’t leave our app nor can we receive from other foreign apps. Let’s see a really simple example of how to use it:

// generally in your onResume()
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("foo");
        Log.d("TAG", "foo : " + message);
}, new IntentFilter("LOCAL-HELLOWORLD"));

We saw how to register, now here’s how to send an intent to it:

// send
Intent intent = new Intent("LOCAL-HELLOWORLD");
intent.putExtra("foo", "bar");

Based on the action set which is LOCAL-HELLOWORLD, it’ll send the intent to our registered receiver to which we had passed an IntentFilter with the same action name.

We shouldn’t forget to unregister the receiver actually. So if we’re saving the receiver in an instance member called myReceiver then here’s how we should unregister it in onPause():

protected void onPause() {

How to update UI from BroadcastReceiver

A BroadcastReceiver can be used in many ways but when it comes to something as specific as updating the UI components of an Activity, there is little advantage to declaring/defining a BroadcastReceiver in it's own Java class file.

Reasoning - the BroadcastReceiver has to have some prior "knowledge" of the Activity and what it is required to do in order to update the UI. In effect the BroadcastReceiver is tied to the Activity itself and it makes sense to declare/define it as an inner class.

Another important aspect is the Activity needs to be in a "running" (i.e., visible) state in order to guarantee manipulation of UI components. In this case, registering the receiver in onResume() and unregistering in onPause() will help prevent problems.

class MyActivity extends Activity {
    MyBroadcastReceiver myReceiver = null;

    protected void onResume() {
        if (myReceiver == null)
            myReceiver = new MyBroadcastReceiver();
        registerReceiver(myReceiver, new IntentFilter("YourIntentAction"));

    protected void onPause() {
        if (myReceiver != null) {
            myReceiver = null;

    private void updateUI(Intent intent) {
        // do what you need to do

    private class MyBroadcastReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {

Obtaining Results from a Broadcast

When a broadcast intent is sent using the sendBroadcast() method, there is no way for the initiating activity to receive results from any broadcast receivers that pick up the broadcast. In the event that return results are required, it is necessary to use the sendOrderedBroadcast() method instead. When a broadcast intent is sent using this method, it is delivered in sequential order to each broadcast receiver with a registered interest.

The sendOrderedBroadcast() method is called with a number of arguments including a reference to another broadcast receiver (known as the result receiver) which is to be notified when all other broadcast receivers have handled the intent, together with a set of data references into which those receivers can place result data. When all broadcast receivers have been given the opportunity to handle the broadcast, the onReceive() method of the result receiver is called and passed the result data.

Sticky Broadcast Intents

By default, broadcast intents disappear once they have been sent and handled by any interested broadcast receivers. A broadcast intent can, however, be defined as being "sticky". A sticky intent, and the data contained therein, remains present in the system after it has completed. The data stored within a sticky broadcast intent can be obtained via the return value of a call to theregisterReceiver() method, using the usual arguments (references to the broadcast receiver and intent filter object). Many of the Android system broadcasts are sticky, a prime example being those broadcasts relating to battery level status.

A sticky broadcast may be removed at any time via a call to the removeStickyBroadcast() method, passing through as an argument a reference to the broadcast intent to be removed.


Broadcast intents are a mechanism by which an intent can be issued for consumption by multiple components on an Android system. Broadcasts are detected by registering a Broadcast Receiver which, in turn, is configured to listen for intents that match particular action strings.

In general, broadcast receivers remain dormant until woken up by the system when a matching intent is detected. Broadcast intents are also used by the Android system to issue notifications of events such as a low battery warning or the connection or disconnection of external power to the device.

Useful links