How To Register BroadcastReceiver In Android Activity

This example will show you how to dynamically register / unregister broadcast receiver in android activity. You can read article Android Broadcast Overview to learn basic concepts about android broadcast if you need.

how to register broadcastreceiver in android activity example

1. Example Execution Steps.

  1. Click the button in this example to open android Settings panel. Below is the java code about how to open Settings in android programmatically.
    // Below code will open android Settings panel programmatically.
    Intent intent = new Intent(Settings.ACTION_SETTINGS);
    startActivity(intent);
  2. Click Data usage go to data usage panel.
  3. Turn on / off Cellular data toggle button to see the toast popup at the bottom of the screen.

2. Create Custom Broadcast Receiver.

Create a java class which extend android.content.BroadcastReceiver, and override it’s onReceive(Context context, Intent intent) method.

NetworkChangeReceiver.java

package com.dev2qa.example.broadcast.receiver;

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

/**
 * Created by Jerry on 1/3/2018.
 */

public class NetworkChangeReceiver extends BroadcastReceiver {

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

        // Get system service object.
        Object systemServiceObj = context.getSystemService(Context.CONNECTIVITY_SERVICE);

        // Convert the service object to ConnectivityManager instance.
        ConnectivityManager connectivityManager = (ConnectivityManager)systemServiceObj;

        // Get network info object.
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        // Check whether network is available or not.
        boolean networkIsAvailable = false;

        if(networkInfo!=null)
        {
            if(networkInfo.isAvailable())
            {
                networkIsAvailable = true;
            }
        }

        // Display message based on whether network is available or not.
        String networkMessage = "";
        if(networkIsAvailable)
        {
            networkMessage = "Network is available";
        }else
        {
            networkMessage = "Network is not available";
        }

        // Use a toast to show network status info.
        Toast.makeText(context, networkMessage, Toast.LENGTH_LONG).show();
    }
}

3. Register And Unregister Broadcast Receiver In Activity.

Now create an activity class and register network change receiver to listen to network change android system broadcast in activity onCreate() method.

READ :   How To Add Contact In Android Programmatically

Do not forget to unregister the network change receiver in activity onDestroy() method.

DynamicRegistReceiverActivity.java

package com.dev2qa.example.broadcast.dynamic;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.dev2qa.example.R;
import com.dev2qa.example.broadcast.receiver.NetworkChangeReceiver;

public class DynamicRegistReceiverActivity extends AppCompatActivity {

    private NetworkChangeReceiver networkChangeReceiver = null;

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

        // Create an IntentFilter instance.
        IntentFilter intentFilter = new IntentFilter();

        // Add network connectivity change action.
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        // Set broadcast receiver priority.
        intentFilter.setPriority(100);

        // Create a network change broadcast receiver.
        networkChangeReceiver = new NetworkChangeReceiver();

        // Register the broadcast receiver with the intent filter object.
        registerReceiver(networkChangeReceiver, intentFilter);

        // Get the button.
        Button openSettingsPanelButton = (Button)findViewById(R.id.open_android_settings_panel_button);
        openSettingsPanelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // When this button is clicked it will open android Settings panel programmatically.
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // If the broadcast receiver is not null then unregister it.
        // This action is better placed in activity onDestroy() method.
        if(this.networkChangeReceiver!=null) {
            unregisterReceiver(this.networkChangeReceiver);
        }
    }
}

4. Add Access Network State Permission In AndroidManifest Xml File.

Because the network change broadcast receiver will listen to android.net.conn.CONNECTIVITY_CHANGE broadcast, so you need to add android.permission.ACCESS_NETWORK_STATE permission in AndroidManifest.xml file. Otherwise you will get below security error message when you run the example.

Caused by: java.lang.SecurityException: ConnectivityService: Neither user 10084 nor current process has android.permission.ACCESS_NETWORK_STATE.

android access network state permission error

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.example">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".broadcast.dynamic.DynamicRegistReceiverActivity">
            <intent-filter android:priority="100">
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
(Visited 4,053 times, 9 visits today)

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.