How To Register BroadcastReceiver In Android Activity

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

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/Oxks0wINZa8

1. Example Execution Steps.

  1. Click the button in this example to open the 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 to go to the data usage panel.
  3. Turn on / off the Cellular data toggle button to see the toast popup at the bottom of the screen.
  4. Below are the example project source files.
    ./
    ├── app
    │   ├── build.gradle
    │   ├── proguard-rules.pro
    │   └── src
    │       ├── main
    │       │   ├── AndroidManifest.xml
    │       │   ├── java
    │       │   │   └── com
    │       │   │       └── dev2qa
    │       │   │           └── example
    │       │   │               ├── broadcast
    │       │   │               │   ├── activity
    │       │   │               │   │   ├── DynamicRegistReceiverActivity.java
    │       │   │               │   ├── receiver
    │       │   │               │   │   ├── NetworkChangeReceiver.java
    

2. Create Custom Broadcast Receiver.

  1. Create a java class that extends android.content.BroadcastReceiver, and override it’s onReceive(Context context, Intent intent) method.
  2. 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;
    
    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.

  1. Now create an activity class and register network change receiver to listen to network change android system broadcast in the activity’s onCreate() method.
  2. Do not forget to unregister the network change receiver in the activity onDestroy() method.
  3. DynamicRegistReceiverActivity.java
    package com.dev2qa.example.broadcast.activity;
    
    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.

  1. 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 the 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.
  2. 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>
5 1 vote
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x