Saturday, 1 March 2014

Understanding BROADCAST RECEIVERS in Android : PART 1


BROADCAST means simply an announcement of an event or something is happened. Broadcasting of announcements/messages can be done by 2 ways in Android.

1. By System: Android System can pass an announcement to all the installed applications saying something is happened. For ex: CONNECTIVITY_CHANGE is one of the announcements by Android system  i.e. whenever there is change in connection availability, system sends/passes an announcement to all the applications installed on device. So all the receivers (means applications) who are interested to respond to corresponding event will get triggered and reacts (More on this shortly). BATTERY_LOW, BOOT_COMPLETED are some of other examples of system broadcasts/announcements.

2. By User: User also can pass an announcement to all the installed applications saying something is happened. For ex: On click of a button OR on successful download of a file we can pass an announcement. So the receivers who are intended to receive this announcement can receive the message and react.

NOTE: All the receivers (I mean Applications) who are registered /intended to respond an announcement/event will receive it even when the apps are not running currently. So the receiver applications need not be running currently when the user/system broadcasts an announcement/event.

In PART 1, I’m going to discuss about the broadcasts By System.  Broadcasts By User in PART2.

Registering the Receiver :
In order to make your application receive an announcement passed by user/system you should register your application for that event. This registration can be done in 2 ways.

1.       In Manifest:  We can register a receiver  using  <receiver> tag for an event in manifest.
 For ex : You can register for CONNECTIVITY_CHANGE event as below.
    <receiver android:name=".MyConnectivityReceiver" >
    <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
  </receiver>

Here android.net.conn.CONNECTIVITY_CHANGE is name of the event which must be specified using intentfilters to react to that event. And MyConnectivityReciever is the receiver class which is going to take over the reacting job when the connectivity change event announced by the system.   

2.       In Activity:  We can also register a receiver dynamically in an activity using registerReceiver() method as below.  You need to create an object of your receiver class and pass as one of the arguments to the method.

IntentFilter iff= new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(yourReceiverClassObject, iff);

 Generally IntentFilters are used to specify how the components (activities/services) of other applications that wish to invoke your component via a specified action. Here we used IntentFilters to specify the event name  i.e. Since Android system sends a broadcast with the action name android.net.conn.CONNECTIVITY_CHANGE when there is a change in connectivity state we must register  our receiver with the same action name in order to make your application respond to connectivitychange event. So now the question is What are the  action names of other events broadcasted by Android system? There are several system events available in the Intent class and other system classes like TelephonyManager.

Implementing the Receiver:  We can implement the receiver part by sub classing BroacastReceiver class and override onReceive() method.

public class MyConnectivityReceiver extends BroadcastReceiver{
      @Override
      public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,
        "Connectivity state changed", Toast.LENGTH_SHORT).show();
           
        //The task to do when the connectivity change happens.
      }
}
So, now our application is ready to receive the event of connectivity change broadcasted by Android system. So, whenever your device goes from online to offline and offline to online the onReceive() of your receiver class will get execute (even when your app is not running currently).

Unregistering the Receiver :  You can unregister the receiver using unregisterReceiver(yourReceiverClassObject) ; call in your activity. This call removes all the filters that have been registered for this receiver. So from now onwards your application is no more responsive for connectivitychange event.

Priority  to Receiver: Assume we have registered more than one application for the same event. When the Android system broadcasts an event, all the receiver apps that are registered to receive the event will trigger asynchronously. If you want to make your application receive the event first among all others then you can use priority like below  

   <receiver android:name=".MyConnectivityReceiver" >
   <intent-filter android:priority = “100”>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
   </intent-filter>
 </receiver>

So the receiver whose priority is high will get triggered first among all others and the receiver without priority or least priority will get triggered last. If you are registering the receiver dynamically then you can set the priority as below.

IntentFilter iff = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
iff.setPriority(100);
registerReceiver(yourReceiverClassObject, iff); 

Generally the suggested place for registering the receiver in an activity is onResume() and for unregistering the receiver is onPause().

No comments:

Post a Comment