Android BroadCast Receiver Example Tutorial

Android BroadCast Receiver Example Tutorial thumbnail
16K
By Sanjeev K. Saroj 02 April, 2017

This tutorial is about creating BroadCastReceiver in android application.Starting from what is Broadcastreceiver, how to create Broadcastreceiver, difference types of Broadcastreceiver and registering receiver, we will also discuss about how network is connected and disconnected using broadcast receiver. We will learn it by creating a simple android broadcaster example here.

What is BroadcastReceiver.

Broadcastreceiver is very important component of android listens to system-wide broadcast 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. BroadcastReceiver doesn’t contain any user interface.

BroadcastReceiver class enables the developer to handle the situation on occurence of the event/action . Action can be arrival of msg or call , download complete , boot completed newtwork connected and disconnected , etc. There are several system generated events defined as final static fields in the Intent.

Following are the lists of few important system events.

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

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

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

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

5.android.intent.action.CALL: To perform a call to someone specified by the data

6android.intent.action.DATE_CHANGED : The date has changed

7android.intent.action.REBOOT : Have the device reboot.

8android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is changed(or reset)

In this post basically we will discuss about connectivity change broadcastreceiver in details.

 Other Interesting Posts
CreateCustom Adpter in List view
Android Asynctask Example
Android Service Example

How to Create BroadCastReceiver

Following will be the project structure.

android-broadcast-receiver

Create a class NetworkChangeReceiver which extends BroadCastReceiver.BroadCastReceiver is an abstract class so we have to implements abstract methods onReceive() of this class. Whenever an event occurs Android calls the onReceive() method on all registered broadcast receivers. If you notice the Intent object is passed with all the additional information required and also you’ve the Context object available to do other tasks like maybe start a service (context.startService(new Intent(this, classname));).

NetworkChangeReceiver.java

public class NetworkChangeReceiver extends BroadcastReceiver {

   @Override
    public void onReceive(Context context, Intent intent) {
      
       }
}

Registering the BroadcastReceiver

A BroadcastReceiver can be registered in two ways:

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

  <receiver android:name=".NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

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

2.By Definig programmatically.

   Intent intnt = new Intent(NETWORK_SWITCH_FILTER);
                intnt.putExtra("is_connected",true);
                context.sendBroadcast(intnt);
				

Here this tag is used for registering public static final String NETWORK_SWITCH_FILTER = "com.devglan.broadcastreceiver.NETWORK_SWITCH_FILTER";

Registering broadcast in android

 registerReceiver(netSwitchReceiver,new IntentFilter(NETWORK_SWITCH_FILTER));

this method is used to register register broadcast receiver.

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

   unregisterReceiver(netSwitchReceiver);

Following is to provide user interface to see the internet connected or not when we switch wifi button or mobile data.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.devglan.broadcastreceiver.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Network connected"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="30sp"/>


This Activity is a launcher activity from here we can check Brodcast send from one activity to another activity is register and unregister.

MainActivity.java
package com.devglan.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private boolean isConnectionAvailable;
    public static final String NETWORK_SWITCH_FILTER = "com.devglan.broadcastreceiver.NETWORK_SWITCH_FILTER";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    BroadcastReceiver netSwitchReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isConnectionAvailable =  intent.getExtras().getBoolean("is_connected");
            if (!isConnectionAvailable) {
                if (NetworkErrorActivity.isOptedToOffline()) {

                } else {
                    Intent netWorkIntent = new Intent(MainActivity.span class="kw">this, NetworkErrorActivity.span class="kw">class);
                    startActivity(netWorkIntent);
                }
            } else {
                NetworkErrorActivity.setOptedToOffline(false);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        try {
            registerReceiver(netSwitchReceiver, new IntentFilter(NETWORK_SWITCH_FILTER));
        }
        catch (Exception e){

        }
    }
	
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(netSwitchReceiver);
        }
        catch (Exception e){

        }
    }
}

This class is main class for BroadcastReceiver through which we are sending broadcast in another activity using context.sendBroadcast(intnt) using a specific tag i.e public static final String NETWORK_SWITCH_FILTER = "com.devglan.broadcastreceiver.NETWORK_SWITCH_FILTER"; using same tag we are registering in MainAtivity.java.

NetworkChangeReceiver.java
package com.devglan.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


**
 * Created by sanjeevksaroj on 16/3/17.
 */
public class NetworkChangeReceiver extends BroadcastReceiver {


    public static final String NETWORK_SWITCH_FILTER = "com.devglan.broadcastreceiver.NETWORK_SWITCH_FILTER";

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {

            NetworkInfo networkInfo =
                    (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo.isConnected()) {
                Intent intnt = new Intent(NETWORK_SWITCH_FILTER);
                intnt.putExtra("is_connected", true);
                context.sendBroadcast(intnt);
            }
            else {

                Intent intnt = new Intent(NETWORK_SWITCH_FILTER);
                intnt.putExtra("is_connected",false);
                context.sendBroadcast(intnt);
            }


        }
    }

}

In this activity catching broadcast receiver send from another activity and register and unregister.

NetworkErrorActivity.java
package com.devglan.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class NetworkErrorActivity extends AppCompatActivity {

    private static boolean optedToOffline = false;
	
    public static final String NETWORK_SWITCH_FILTER = "com.devglan.broadcastreceiver.NETWORK_SWITCH_FILTER";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.network_error);

    }

    public static boolean isOptedToOffline() {
        return optedToOffline;
    }
	
    public static void setOptedToOffline(boolean optedToOffline){
        NetworkErrorActivity.optedToOffline = optedToOffline;
    }

    BroadcastReceiver netSwitchReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isConnectionAvailable =  intent.getExtras().getBoolean("is_connected");
            if (isConnectionAvailable) {
                optedToOffline = false;

                finish();
            }

        }
    };
	
    @Override
    protected void onResume() {
        super.onResume();
        try {
            registerReceiver(netSwitchReceiver, new IntentFilter(NETWORK_SWITCH_FILTER));
        }
        catch (Exception e){

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(netSwitchReceiver);
        }
        catch (Exception e){

        }
    }
}

Following xml is to show when network is disconnected.

network_error.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.devglan.broadcastreceiver.NetworkErrorActivity">


<TextView
    android:id="@+id/tv_network"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Network Error"
    android:textSize="30sp"
    android:gravity="center"/>


Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download source

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
Android Developer at Tech Mahindra

Further Reading on Android