I'm building an Android app and a Blackberry app (same app different platforms). There is an abstract class that I am building that will handle events. For instance, I touch the "save" button on Android it posts a notif/event. The abstract class receives that event. I press the "save" button on Blackberry, it does the same thing.
What is the best way to accomplish this? I've looked at EventObject, as well as MBeans and its notification classes but they appear overly complicated. In objective-c I simply register a class instance for notifications with the objective-c notificationcenter, and then in the class that triggers the notif, at the time of trigger we do something along the lines of "postNotification". Is there anything that easy in Java? Also I need to send Objects with those notifications.
Oh at I suppose we actually can't use any MBeans classes. Not part of Blackberry Java version.
Thanks!
With BlackBerry, if you're planning on these events to be generated from UI elements (ButtonField, ListField, etc) they all come with Field.setChangeListener(FieldChangeListener) so you just have to attach a listener to that. If you want this to be something that responds to things like IO or processing, you could use the Event and EventListener classes to accomplish this. Personally I think they're a little more than what I need for simple notifications, so I generally make my own simple interfaces.
Say you have a class that extends Thread that connects to a web service to download an XML file that lists states and their capitals. and processes it. You could create an interface EventGenerator with abstract methods public void addEventHandler(EventHandler)
and protected void notifyHandlers(Object obj)
. Inside of this you have a Vector that stores EventHandlers that your notifyHandlers()
can loop through and send a call to handler.handleEvent(Object)
. When you are finished with processing the data, you wrap it up in an Oject (maybe Hashtable, or a custom States bean), we'll call it states
, and internally call notifyHandlers(states)
. Now as you go through each EventHandler, you call handler.handleEvent(states)
. You may consider putting a try/catch around each call to it so one EventHandler doesn't prevent all of them from running.
So onto the EventHandlers. This is another interface that has the abstract method public void handleEvent(Object obj)
. Say you have a Screen that, after the states
are retrieved, will display them in a list. This Screen will implement EventHandler and then register itself with the EventGenerator using generator.addEventHandler(this)
. Whenever the processing is done, this method will get called and you can do whatever you want with the Object that is returned.
An addition you can implement is changing public void handleEvent(Object obj)
to public boolean handleEvent(Object obj)
and, similarly to navigation methods in BB, return true if the event was handled and nothing else should try processing it.