Understanding Broadcast Receiver Using Xamarin Visual Studio 2015

Introduction

Any Android application is made of four parts -  Activity, Broadcast Receiver, Content Provider, and Service. Broadcast receiver is used for sending a message to same application or another application. Using Broadcast receiver, we can inform the same application or another application for something happening. In this article, we will learn how to create, register, and unregister broadcast receiver. Broadcast receiver can be defined in following two ways.

  • Registering Broadcast Receiver Programmatically
  • Registering Broadcast Receiver in AndroidManifest.xml file
Registering Broadcast Receiver programmatically

Following are the steps for registering Broadcast Receiver programmatically.

Step 1 - Create a new project for Android application


I have selected "Blank App (Android)" from template for this article.

Step 2 - Select layout of Main.axml and sending Broadcast Message

For sending the broadcast message, here, I used one button. When user clicks on “Send Broadcast Message” button, it sends a message to Broadcast Receiver.

Layout of Main.axml is shown below.


MainActivity class is an extended class of Activity (base class). To define the Broadcast Receiver, we need to create class which is extended from "BroadcastReceiver" base class. Here, I have created "MyBroadcastReceiver" class. To receive Broadcast message, we need to override OnReceive() method in this class. Now, in MainActivity class, I have created object of MyBroadcastReceiver class as “myreceiver” and IntentFilter object as “intentfilter”.

  1. Public class MyBroadcastReceiver : BroadcastReceiver  
  2. {  
  3.    Public override void OnReceive(Context context, Intent intent)  
  4.   {  
  5.   }  
  6. }  
To create broadcast message, we need to write the click event of “Send Broadcast Message” button in OnCreate() method of MainActivity, after SetContentView() method. The OnCreate() method of MainActivity is shown below.
  1. Protected override void OnCreate(Bundle bundle)  
  2. {  
  3.     base.OnCreate(bundle);  
  4.     SetContentView(Resource.Layout.Main);  
  5.     Buttonbtnsendmessage = (Button)FindViewById(Resource.Id.sendBroadcast);  
  6.     myreceiver = new MyBroadcastReceiver();  
  7.     intentfilter = new IntentFilter("MY_SPECIFIC_ACTION");  
  8.     btnsendmessage.Click += (sender, e) =>  
  9.     {  
  10.          Intent i = new Intent("MY_SPECIFIC_ACTION");  
  11.          i.PutExtra("key""some value from intent");  
  12.          SendBroadcast(i);  
  13.   
  14.      };  
  15. }  
Step 3 - Registering and unregistering Broadcast Receiver in MainActivity.cs

For registering Broadcast Receiver, we need to use RegisterReceiver() method in OnResume method of MainActivity when MainActivity is ready to interact with user. Also, Unregisterreceiver() method in OnPause() method of MainActivity when MainActivity is in back-grounded. So, when my MainActivity is back, the background Broadcast Receiver will unregister. So, it means that my broadcast receiver will not work when MainActivity is back-grounded. The OnResume() and OnPause() method of MainActivity are shown below.

  1. Protected override void OnResume()  
  2. {  
  3.      base.OnResume();  
  4.      RegisterReceiver(myreceiver, intentfilter);  
  5. }  
  6. Protected override void OnPause()  
  7. {  
  8.      base.OnPause();  
  9.      UnregisterReceiver(myreceiver);  
  10. }  
Step 3 Broadcast Message Receiver

Now, I have defined Alert message in OnRecieve() method of MyBroadcastReceiver class. Following is definition of "OnReceive()" method.

  1. Public class MyBroadcastReceiver : BroadcastReceiver  
  2. {  
  3.     Public override void OnReceive(Context context, Intent i)  
  4.         {  
  5.              Toast.MakeText(context,"Received broadcast in MyBroadcastReceiver, " +  
  6.                                        " value received: " + i.GetStringExtra("key"),  
  7.                                        ToastLength.Long).Show();  
  8.          }  
  9. }  
Output



Registering Broadcast Receiver in AndroidManifest.xml file

In the first method, we cannot use Broadcast receiver when the application is working in the background because I have unregistered Broadcast receiver in OnPause() method.

If you want to use Broadcast receiver in background, the better or good way is to register your Broadcast Receiver in AndroidManifest.xml file.

For this, I have created a new Broadcast Receiver in our project by right clicking on project. Select “Add->New Item”. It will open a new window.

Select Broadcast Receiver and give name as “MySecondBroadcastReceiver”.



It will add new .cs file in your project explorer, as follows.


To register MySecondBroadcastReceiver, add <receiver> tag in AndroidManifest.xml.

  1. <?xmlversion="1.0"encoding="utf-8"?>  
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"package="broadcast_example.broadcast_example"android:versionCode="1"android:versionName="1.0">  
  3.     <uses-sdk android:minSdkVersion="16" />  
  4.     <application android:label="broadcast_example">  
  5. <receiver android:name="broadcast_example.MySecondBroadcastReceiver">  
  6. <intent-filter>  
  7. <action android:name="MY_SPECIFIC_ACTION" />  
  8. </intent-filter>  
  9. </receiver>  
  10. </application>  
  11.       
  12. </manifest>  
Now, I have registered two Broadcast Receivers - one programmatically in OnResume() method and another in AndroidManifest.xml. Now, when I call Broadcast Receiver, both the Broadcast Receivers will be called.

Output


Assigning priorities to Broadcast Receiver

We can add priorities to Broadcast Receiver when more than one Broadcast Receivers are defined. To set priority, you need to define priority to intentfilter in OnResume() method.

  1. Protected override void OnResume()  
  2. {  
  3.       base.OnResume();  
  4.       intentfilter.Priority=20;  
  5.       RegisterReceiver(myreceiver, intentfilter);  
  6. }  
We have given priority to Broadcast Receiver, so instead of SendBroadcast() method in OnCreate() method, we need to use SendOrderedBroadcast() method. Click event of “Send Broadcast Message” button is shown below.
  1. btnsendmessage.Click += (sender, e) =>  
  2. {  
  3.         Intent i = newIntent("MY_SPECIFIC_ACTION");  
  4.         i.PutExtra("key""some value from intent");  
  5.        // SendBroadcast(i);  
  6.         SendOrderedBroadcast(i, null);  
  7. };  
If we register Broadcast Receiver in AndroidManifest.xml, then we need to add priority in <intent-filter>.
  1. <intent-filter android:priority ="20">  
  2.    <action android:name="MY_SPECIFIC_ACTION" />  
  3. </intent-filter>  
Aborting Broadcast

For aborting broadcast, we can use AbortBroadcast() method.

Summary

In this article, we learned the two ways of defining Broadcast Receiver and how to create, register and receive broadcast message using Xamarin Visual Studio 2015. Also, we learned how to set priority and abort broadcast.


Similar Articles