Broadcast Receiver

Broadcast Receiver:

 A broadcast receiver (short receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android run time once this event happens.
For example applications can register for the ACTION_BOOT_COMPLETED system event which is fired once the Android system has completed the boot process.


How To Create Broadcast Receiver

There are two part of Simple creation of Broadcast Receiver.


1. Creating Receiver class: This is created by extending BroadcastReceiver class.

                   public class Receiver extends BroadcastReceiver {

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

                 /*

                             Write here code that you want to execute
                 */
Toast.makeText(context, "I am a Receiver  !", Toast.LENGTH_SHORT).show();
}
}

Note: You can write small time taken code within onReceive(). For large code you have to create Service.


2. Registring Receiver name in AndroidManifest.xml: 
                         A receiver can be registered via the AndroidManifest.xml file.
Alternatively to this static registration, you can also register a broadcast receiver dynamically via theContext.registerReceiver() method.
The implementing class for a receiver extends the BroadcastReceiver class.

If the event for which the broadcast receiver has registered happens the onReceive() method of the receiver is called by the Android system.

 <application
     
        
        <receiver android:name="com.example.broadcastprg.Receiver" >
            <intent-filter>
               <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
          
            </intent-filter>
        </receiver>


Here this Receiver is triggered when device is connected with power resources.

Lifecycle of a broadcast receiver
After the onReceive() of the BroadcastReceiver has finished, the Android system can recycle theBroadcastReceiver.
Before API11 you could not perform any asynchronous operation in the onReceive() method because once theonReceive() method is finished the Android system was allowed to recyled that component. If you have potentially long running operations you should trigger a service for that.
As for API11 you can call the goAsync() method. If this method was called it returns an object of thePendingResult type. The Android system considers the receiver as alive until you call thePendingResult.finish() on this object. With this option you can trigger asynchronous processing in a receiver. As soon as that thread has completed its task is calls finish() to indicate to the Android system that this component can be recycled.

For More information:
                http://developer.android.com/reference/android/content/BroadcastReceiver.html

You can download complete code here



No comments:

Today's Pageviews