Android has the following three ways of sending broadcast messages:
- Using the sendOrderedBroadcast(Intent, String) method sends messages to one receiver at a time. Since receivers execute in order, it's possible to propagate a result to the next receiver. Also, it's possible to abort the broadcast so that it won't be passed to the rest of the receivers. We can control the order in which receivers are executed. We can use the android:priority attribute of the matching intent filter to prioritize.
- Using the sendBroadcast(Intent) method sends broadcast messages to all receivers. The sending is not ordered.
- Using the LocalBroadcastManager.sendBroadcast(Intent) method sends broadcasts to receivers that are in the same application as the sender.
Let's take a look at an example of sending a broadcast message to all interested parties:
val intent = Intent() intent.action = "com.journaler.broadcast.TODO_CREATED" intent.putExtra("title", "Go, buy some lunch.") intent.putExtra("message", "For lunch we have chicken.")
sendBroadcast(intent)
We created a broadcast message containing extra data about note a we created (title and message). All interested parties will need a proper IntentFilter instance for the action:
com.journaler.broadcast.TODO_CREATED
Don't get confused with starting activities and sending broadcast messages. The Intent class is used just as a wrapper for our information. These two operations are completely different! You can achieve the same using the local broadcast mechanism:
val ctx = ... val broadcastManager = LocalBroadcastManager.getInstance(ctx) val intent = Intent() intent.action = "com.journaler.broadcast.TODO_CREATED" intent.putExtra("title", "Go, buy some lunch.") intent.putExtra("message", "For lunch we have chicken.")
broadcastManager.sendBroadcast(intent)
Now, when we showed you the most important aspects of broadcast messaging, we will continue with extending our application. Journaler will send and receive our custom broadcast messages containing data and interact with system broadcasts, such as system boot, shutdown, and network.