The message bus is a tried-and-true model in application development. Whether it is the humble Win32 message loop or full-fledged publish/subscribe message-oriented middleware solution, software components have long been publishing messages that other components receive, either by explicitly checking some message queue or by virtue of the message matching some pattern the receiver subscribed to.
Guess what? The Android system of Intent objects is just a message bus. The principal aim is for the bus to pass around messages related to the system, from media card inserts to requests to perform some action on some piece of content, like a contact. But, the Intent bus can be used by your own activities and other Android components, not only for communicating with Android, but with each other.
In today’s segment of Building ‘Droids, we’ll look subscribing to messages on the bus using an IntentReceiver. Later, we’ll look at sending Intent objects on the bus to be delivered to your receivers, or receivers others might set up.
Activities are set up to receive Intent messages, as defined in AndroidManifest.xml via intent-filter elements. For example, most applications have an activity with an intent-filter set up like this:
To receive your own messages, particularly when you only want them at certain times, you will want to use IntentReceiver. Here’s a quick recipe:
First, come up with the name for the Intent you want. This should be distinct from any other Intent name on the device. The easiest way to ensure this is to have it use your application’s Java namespace, such as:
[sourcecode language=’java’]protected static final String PROXIMITY_ALERT = “com.commonsware.tourit.intent.action.PROXIMITY_ALERT”;[/sourcecode]
Next, create an IntentFilter that will look for Intent instances with your supplied name, such as:
[sourcecode language=’java’]protected final IntentFilter proximityLocationIntentFilter = new IntentFilter(PROXIMITY_ALERT);[/sourcecode]
Then, create your own concrete subclass of Android’s IntentReceiver class, implementing onReceiveIntent(). This method receives a Context (e.g., the Activity instance where you created this IntentReceiver) and the Intent message that arrived. It is up to you to do something useful with that message, such as update an activity’s UI (be sure to do this on the UI thread!) or update a SQLite database.
Finally, when you want your IntentReceiver to watch for messages, call registerReceiver() in your Activity or other Context, providing it the IntentReceiver and IntentFilter, such as:
private ProximityIntentReceiver receiver=new ProximityIntentReceiver();
Later on, when you no longer need to receive the messages, call unregisterReceiver() with the same IntentReceiver instance you used with registerReceiver().
In our next episode, we’ll see how to set up a component to send messages on the Intent bus.