Broadcast Receiver

Table of Contents

  1. Introduction
  2. Creating the broadcast receiver
  3. Registering broadcast receiver
  4. Creating and registering broadcast receiver dynamically
  5. Broadcasting Custom Intents
  6. Broadcast methods
  7. sendBroadcast() with permissions
  8. sendOrderedBroadcast() to get feedback from receivers
  9. Force the bradcast receive order
  10. Restrictions for defining broadcast receiver
  11. Asynchronous processing
  12. Examples of system generated events
  13. Working example


A broadcast receiver is an Android component which allows you to register for system or application messages called also events or intents. All receivers registered for a given message (event) are notified by the Android runtime once this event happens.For example, applications can register for the SMS_RECEIVED event which is fired once the sms messsage is recieved. Broadcast receiver is this who will intercept this event and will initiate appropriate action.

We can register for predefined events but, what is more important, we can also defined and emmit our own events.

Generaly there are two steps to make broadcast receiver works for the systen broadcasted intents:

  1. Creating the Broadcast Receiver.
  2. Registering Broadcast Receiver

There is one additional steps in case you are going to implement your custom events then you will have to create and broadcast those events.

Creating the Broadcast Receiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter.

Registering Broadcast Receiver

A receiver can be registered via the AndroidManifest.xml file.

Creating and registering broadcast receiver dynamically

Alternatively to the static registration, you can also create and register a receiver dynamically via the Context.registerReceiver() method.

Notce that dynamic registration allows to listen for events only when our application is active. When receiver is registered with manifest file, our applicarion would be executed even when is inactive (in oher words, we listen for events all the time).

Broadcasting Custom Intents

If you want your application itself can generate and send custom events. You have to create and send such an events by using the sendBroadcast() method inside your activity class.

The event some.unique.url.CUSTOM_EVENT can also be regsitered in similar way as we have regsitered system generated events so far. Remember to use unique name for your event (best practice is to use url in reverse oreder).

Broadcast methods

There are few different methods which allows to broadcast events.

  1. sendBroadcast(Intent intent) This is the simplest form of broadcast sending method. Broadcast the given intent to all interested BroadcastReceivers.
  2. sendBroadcast(Intent intent, String receiverPermission) Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.
  3. sendOrderedBroadcast(Intent intent, String receiverPermission) Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers.
  4. sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) Version of sendBroadcast(Intent) that allows you to receive data back from the broadcast.

When a broadcast intent is sent using the sendBroadcast() method, there is no way for the initiating activity to receive results from any broadcast receivers that pick up the broadcast. If the return results are required, it is necessary to use the sendOrderedBroadcast() method instead. When a broadcast intent is sent using this method, it is delivered in sequential order to each broadcast receiver with a registered interest.The sendOrderedBroadcast() method is called with a number of arguments including a reference to another broadcast receiver (sendOrderedBroadcast(..., BroadcastReceiver resultReceiver, ...)), known as the result receiver, which is to be notified when all other broadcast receivers have handled the intent, together with a set of data references into which those receivers can place result data. When all broadcast receivers have been given the opportunity to handle the broadcast, the onReceive() method of the result receiver is called and passed the result data.

sendBroadcast() with permissions

Sending broadcats with permissions is not complicated

More important is to correctly controll the permissions. In one application, tipically broadcast sender, we have to define permissions

while in other, typically receiver(s), we have to ask for a permission(s) that the application must be granted in order for it to operate correctly.

Note that we may also declare the element in both apps, so the order of their installation does not matter. Otherwise, the app has to be installed before the app.

sendOrderedBroadcast() to get feedback from receivers

See the complete example below for  details about sendOrderedBroadcast()

Force the broadcast receive order

Code above allows us to define the order in which receivers would be called. Always the last receiver is the receiver which is registered dinamically.

Restrictions for defining broadcast receiver

As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the the application manager on the device. This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents. This does not mean the user has to start the application again after a reboot. The Android system remembers that the user already started it. Only one start is required without a forced stop by the user. To get around this, however, a flag can be added to the intent before it is sent to indicate that the intent is to be allowed to start a component of a stopped application. This flag is FLAG_INCLUDE_STOPPED_PACKAGES

Asynchronous processing

Before API level 11, you could not perform any asynchronous operation in the onReceive() method, because once this method had been finished, the Android system was allowed to recycle that component. In such a case if you have potentially long running operations, you should trigger a service instead.Since Android API 11 you can call the goAsync() method. This method returns an object of the PendingResult type. The Android system considers the receiver as alive until you call the PendingResult.finish() on this object. With this option you can trigger asynchronous processing in a receiver. As soon as that thread has completed, its task calls finish() to indicate to the Android system that this component can be recycled.

Examples of system generated events

Event Constant Description
android.intent.action.BATTERY_CHANGED Sticky broadcast containing the charging state, level, and other information about the battery.
android.intent.action.BATTERY_LOW Indicates low battery condition on the device.
android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low.
android.intent.action.BOOT_COMPLETED This is broadcast once, after the system has finished booting.
android.intent.action.BUG_REPORT Show activity for reporting a bug.
android.intent.action.CALL Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON The user pressed the “call” button to go to the dialer or other appropriate UI for placing a call.
android.intent.action.DATE_CHANGED The date has changed.
android.intent.action.POWER_CONNECTED Power got connected to the device.
android.intent.action.POWER_DISCONNECTED Power got disconnected to the device.
android.intent.action.REBOOT Have the device reboot.
android.intent.action.TIME_TICK Event send every minute to indicate that time has changed.
android.provider.Telephony.SMS_RECEIVED Indicates the SMS was received.

Working example







Leave a Reply

Your email address will not be published. Required fields are marked *