7.3 Broadcasts & BroadcastReceivers Flashcards
Learn about the theory and implementation of Broadcasts and BroadcastReceivers
Broadcast Definition
Messaging components used for communicating when an event of interest occurs
BroadcastReceiver Definition
The components in you app that listen for app or system events and respond accordingly
What are the different types of broadcasts
- System broadcasts: delivered by the system
2. Custom broadcasts: delivered by your app
How do system broadcasts work?
These broadcasts are wrapped in an Intent object:
- The intent object’s action field
contains event details
-(e.g. android.intent.action.HEADSET_PLUG)
- Intents can also contain more data
about the event in the extra field
-(e.g.as a boolean for whether or not the
headset is connected or disconnected )
What must an application do to receive a system broadcast?
Interested apps must register a component to “listen” for these events via a BroadcastReceiver
When do you use custom broadcasts?
When you want your ap to take action without launching an activity.
For example, to let other apps know that data has been downloaded and it’s available for those apps.
What are the different types of custom broadcasts?
- Normal broadcasts
- Ordered broadcasts
- Local broadcasts
What are the methods associated with the different types of custom broadcasts?
- Normal broadcasts:
sendBroadcast( ) - Ordered broadcasts:
sendOrderedBroadcast( ) - Local broadcasts:
LocalBroadcastManager.sendBroadcast( )
What makes normal broadcasts different from the other types?
It sends broadcasts to all registered receivers simultaneously, in an undefined order.
They can’t propagate (spread) the results among themselves
They cannot cancel the broadcast
An example of a normal broadcast
public void sendBroadcast() { Intent intent = new Intent(); intent.setAction("com.example.myproject.ACTION_SHOW_TOAST"); // Set the optional additional information in extra field. intent.putExtra("data","This is a normal broadcast"); sendBroadcast(intent); }