Monday, December 5, 2011

Some really simple messaging

Update:
The approach below will work, but Roboguice's Events are more elegant.

I've been working through my first non-trivial Android app, and had a need for some simple messaging (Intents didn't seem like a good fit for simple, internal, app messages). I came up with the following classes. IMessage is simply a message object whose type is identified by a string. My favorite implementation is an enum, but any class would do. Here's a simple message: ISubscriber<T extends IMessage> describes a simple class which subscribes to a message, having its onMessage() method invoked when that message arrives. Here's a snippet of an activity and a subscriber: IBus simply connects up the messages and subscribers, here's my simple implementation of that. This approach works best if the IBus implementation lives outside the scope of an Activity. I've had good luck with instantiating the above Bus and injecting it where needed via Roboguice. There's probably an easier way to send simple messages around, but this is what I'm using until I find that :) Here's the source-code for a simple test app outlining the above approach.