ANDROID training: broadcast receivers
Broadcast receivers are something which will get triggered on some broadcasted message. One can choose to respond to those broad cast messages by registering the receiver to react to that action which has been broad casted.
In case of activities and services, only one component will be triggered for any intent, that is intended for an activity or service.
But if you see the architecture of the broadcast receivers, more than one receiver can get triggered if all of those receivers satisfy the condition of intent-filter testing.
Which means there is a possibility of getting more than one receiver executed for a given broadcast message.Eg: may be more than one application is listening for a broadcast message say “INCOMING_SMS”. Then all those receivers will get executed.
There are two ways to create broadcast receivers:
- statically – in manifest <receiver>
- dynamically – in code using context.registerreceiver
Note: if you have registered a broadcast receiver in – on resume
Then you should unregister it in on pause
There are three kinds of broadcasts:
- Normal broadcasts - Context.sendBroadcast
- Ordered broadcasts - Context.sendOrderedBroadcast – android:priority
- Sticky broadcasts – Context.sendStickyBroadcast – sticky intent
In case of normal broadcasts, order in which receivers will get executed will not be known. They may get executed parallel or one by one or in some random order.
Where as in case of ordered broadcasts, they will get executed one by one based on the priority given to those components. If two components have same priority then order can’t be predicted.
In case of sticky broadcasts, it acts exactly like sending broadcast by only difference is the intent which you have previously sent will be hold by android. so that if any one calls registerreceiver(intentfilter) with the same action, then
note: Even in the case of normal broadcasts, the system may in some situations revert to delivering the broadcast one receiver at a time
Broadcast Receiver Lifecycle
Valid for the duration of the call to onReceive(Context, Intent)
So, anything that requires asynchronous operation is not available
Because, android will kill that process once control returns from receiver.
e.g. you may not show a dialog or bind to a service from within a Broadcast Receiver.
you should instead use the Notification Manager