Sunday, December 28, 2014

Android Broadcast Receiver - Part 1


A broadcast receiver allows application to register for System or application events. All registered receivers are notified by the Android system when the event happens. 
For e.g application can register for ACTION_BOOT_COMPLETED system event which is fired once Android system has completed boot process. 

Receivers can be implemented by 

1. Specifying a receiver in the AndroidManifest.xml file. This is called static registration 
2. Also, apps can do dynamic registration by calling Context.registerReceiver() method. 

The implementation class should extend the BroadcastReceiver class. When the event for which the receiver class has registered happens, the Android system calls the onReceive() is called by the Android System. 
After onReceive is called by the Android system, the Android system likely to recycle the receiver instance. 

Before API level 11, Application was not allowed to perform any asynchronous operation in the onRecieve method because the System likely to destroy the receiver instance. 
Since API 11, receiver implementation can call the goAsync method. This method returns the PendingResult type. Android system considers the receiver to be alive until the PendingResult.finish is called. 

As of Android 3.1, the android system excludes all receiver from receiving the broadcast intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via 
Android menu (in Manage -> Application.

This is an additional safety as the user can be sure that only the applications he started will be able receive broadcast intents. However, in previous device boot session if the app was not killed by the user, then Android system 
gives the boot event to the receiver 

System Broadcasts
Several system events are defined as static fields in Intent class. Other android system classes also define events. e.g. the TelephonyManager defines events for the change of phone state. The following are the list of important events

Intent.ACTION_BOOT_COMPLETED => Boot completed. Requires android.permission.RECEIVE_BOOT_COMPLETED 
Intent.ACTION_POWER_CONNECTED => Power connected to the device 
Intent.ACTION_POWER_DISCONNECTED => Power disconnected from device. 
Intent.ACTION_BATTERY_LOW => Triggered on battery low. Typically can be used to reduce battery intense operations. 
Intent.ACTION_BATTERY_OKAY => When battery is at good level. 


references:
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#broadcastreceiver_definition

No comments:

Post a Comment