Learn Android Development For Beginners

Broadcast Receiver

A Broadcast receiver is an Android Component which allows you to register for system or application events. Android Runtime notifies all the registered receivers once that event occurs. For example application can register the events for Message Received, Phone call received and On Boot Completed.

Application can also initiate broadcasts to let other application knows about something important e.g. data is ready to use for them.

Android system and other applications broadcasts messages time to time to inform about things that are happening e.g. boot is completed, Receive Phone call, Data is loaded etc.

How to Create Broadcast Receiver

There are only two steps require to create a Broadcast receiver.

1. Create Broadcast Receiver Class

Create subclass of the “BroadcastReceiver” class and override the “onReceive” method where each message is received as Intent. E.g. Create a Broadcast Receiver to receive method when Boot is completed.

 public class MyBootCompleteReceiver extends BroadcastReceiver {

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

        Toast.makeText(context, " MyBootCompleteReceiver: System is Ready to Use.", 
                                                         Toast.LENGTH_LONG).show();


    }
 }

Android system calls the onReceive method of the registered component and passes the intent and context to get extra information.

2. Register Broadcast receiver

Same as Activity Broadcast receiver is also need to be declared in the AndroidManifest.xml file. Add the <receiver> element in the <application> element and set the intent message type on which the receiver method will be invoked. Register MyBootCompleteReceiver class in the Manifest file and set the intent action type as android.intent.action.BOOT_COMPLETED .

 <receiver android:name=".MyBootCompleteReceiver">
       <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
       </intent-filter>
 </receiver>

Application can also register receiver dynamically from code. registerReceiver() method use for registering the receiver and unregisterReceiver() method use for unregistering the receiver dynamically.

For registering the receiver dynamically create the instance of “MyBootCompleteReceiver” broadcast receiver class and then create the Intent instance and add your required action e.g Intent.ACTION_BOOT_COMPLETED using addAction() method and pass these two as a parameter to registerReceiver() method.

 // Create Receiver Object
 BroadcastReceiver receiver = new MyPowerReceiver();

 //Create Intent Filter
 IntentFilter intentFilter = new IntentFilter(); 
 intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);

// Register broadcast receiver
this.registerReceiver(receiver, intentFilter);

Application can also need permissions for accessing or receiving specific messages or events e.g. “ACTION_BOOT_COMPLETED” event require a RECEIVE_BOOT_COMPLETED permission declared in Manifest file.

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

Write Your First Broadcast Receiver for WIFI

Create a new application and name it MyFirstBroadCastReceiver. Add new class MyWifiReceiver in the package folder under java folder. Extend the class from BroadcastReceiver and override onReceive() method and write the code in this method to check connect and disconnect.

 public class MyWifiReceiver  extends BroadcastReceiver {

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

        ConnectivityManager conMngr = (ConnectivityManager)context.getSystemService(
                                                        context.CONNECTIVITY_SERVICE);
        
        android.net.NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  
        boolean conntected = false;
        if(wifi!=null)
        {
            String state = "";

            switch(wifi.getState())
            {
                case CONNECTED:{
                    state = "Connected";
                    break;
                }

                case CONNECTING:{
                    state = "Connecting";
                    break;
                }

                case DISCONNECTED:{
                    state = "DisConnected";
                    break;
                }
            }


            conntected = wifi.isConnected();
            String message= "MyWifiReceiver: wifi is " + state;
            Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
        }

    }

 }

The ConnectivityManager class contains the state of the network connectivity. Application can get the instance of that class using “context.getSystemService(context.CONNECTIVITY_SERVICE)” method.

Get the Wifi network information form ConnectivityManager using getNetworkInfo(ConnectivityManager.TYPE_WIFI) method and get the current Status of the WIFI.

After creating the BroadcastReceiver class, now register the receiver in AndroidManifest.xml file. Add the <receiver> element and provide the receiver class name in android:name=".MyWifiReceiver" attribute. Register the intent filter event that invoke the onReceive() method of receiver class.

 <receiver android:name=".MyWifiReceiver">
     <intent-filter>
          <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
          <action android:name="android.net.wifi.STATE_CHANGE"/>
     </intent-filter>
 </receiver>

For accessing the network status application requires following permissions declared in AndroidManifest.xml file

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

Now WIFI broadcast receiver is ready to use and once the program is installed in the machine. Android system will register the WIFI status change receiver and whenever the WIFI status changes, you will see message on your Android machine screen.

Write Program to Broadcast Custom Intent

Add new class MyCustomReceiver in the package folder under java folder. Extend the class from BroadcastReceiver and override onReceive() method to write receiver code.

 public class MyCustomReceiver extends BroadcastReceiver {

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

        CharSequence message = intent.getCharSequenceExtra("message");
        Toast.makeText(context, "MyCustomReceiver received  message: " + message, 
                                                                Toast.LENGTH_LONG).show();

    }

 }

When application broadcasts this intent/action, it also passes the “message” in it. Get the message from Intent and display it.

Declare the MyCustomReceiver receiver in the AndroidManifest.xml file and set the name of custom intent as “com.example.myfirstbroadcastreceiver.MY_CUSTOM_INTENT”. The application will set this action name when it will broadcast message.

 <receiver android:name=".MyCustomReceiver">
       <intent-filter>
           <action android:name="com.example.myfirstbroadcastreceiver.MY_CUSTOM_INTENT"/>
       </intent-filter>
 </receiver>

Now add the Button and text box for the message in the layout file. Register on click event to broadcast the message written in the text box.

 Button btnSend = (Button)findViewById(R.id.btnSend);

 btnSend.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        broadcastCustomIntent();
    }

 });

In broadcastCustomIntent() method create the Intent and pass the message using putExtra() method. pass the action name using setAction() method. Call the sendBroadcast(intent) of the context to broadcast the message.

 public void broadcastCustomIntent()
 {
    Intent intent = new Intent("MyCustomIntent");
    EditText et = (EditText)findViewById(R.id.txtMessage);
    
    // add data to the Intent
    intent.putExtra("message", (CharSequence)et.getText().toString());
    intent.setAction("com.example.myfirstbroadcastreceiver.MY_CUSTOM_INTENT");
    
    sendBroadcast(intent);
 }

Run the program, Enter you message and press the Send button, Application will show the message on the screen.

custom Broadcast Receiver

On the click of the button, application broadcasts the message, Android System get this message and invoke the OnReceive method of the registered receivers.

Register Receiver Dynamically (in code)

In the previous examples, all the receivers are registered in AndroidManifest.xml file. You can also register and unregister receivers dynamically from code file. In the next example we will register broadcast receiver for Power connected and disconnected. System broadcast message whenever power is connected and disconnected.

Create the new class MyPowerReceiver subclass of BroadCastReceiver and override its onReceive method.

 public class MyPowerReceiver extends BroadcastReceiver {

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

       if(intent.getAction() == Intent.ACTION_POWER_CONNECTED)
       {
          Toast.makeText(context, "MyPowerReceiver: Power is Connected.", 
                                                      Toast.LENGTH_LONG).show();
       }
        else
       {
           Toast.makeText(context, "MyPowerReceiver: Power is Dis-connected.", 
                                                        Toast.LENGTH_LONG).show();
       }

    }

 }

You can check the current action using the intent.getAction() method. If current action is Intent.ACTION_POWER_CONNECTED, its mean power is just connected otherwise power is disconnected.

For registering the Broadcast Receiver call the registerReceiver() method of the context and pass the Broadcast Receiver and intent as a parameters. Create the IntentFilter object and add ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED as action using addAction method.

 public void registerPowerStatusChangeReceiver()
 {

     // Create Receiver Object
     BroadcastReceiver receiver = new MyPowerReceiver();

     //Create Intent Filter
     IntentFilter intentFilter = new IntentFilter();

     intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
     intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);

     // Register broadcast receiver
     this.registerReceiver(receiver, intentFilter);

 }

There is also method unregisterReceiver() available for the unregistering the broadcast receiver. Pass the broadcast receiver object that was registered before for unregister.

If any broadcast receiver required special permissions, , add those permissions in the AndroidManifest.xml file.

Download Source Code

You can get the source code. Download Source Code

;