开发者

Newbie Java developer questions - inter class communication with events

Please forgive the very basic nature of this questions - but we all have to start somewhere. I've done some googling but all answers seem to relate to UI Events.

I am creating a very simple android app that will display your location on screen. I have my main class (HelloAndroid at 开发者_运维技巧the moment) that extends Activity and I have created a class LcoationUpdateHandler that listens for updates.

HelloAndroid holds an instance of LocationUpdateHandler so my question is how does the LocationUpdateHandler communicate with HelloAndroid.

In flex I would dispatch an event from one to the other but from the searching I have done this doesn't seem like a very java-y way of doing things?

Thanks for your help.


When your HelloAndroid instance creates an instance of LocationUpdateHandler it can pass a reference to itself in the constructor, which LocationUpdateHandler can store to use for future method calls in the case of events.

For these kinds of situations you don't really need to know what type of object instatiated LocationUpdateHandler. This is were interfaces come in, you can define an interface defining the event methods and implement that interface so that LocationUpdateHandler can keep a reference to that interface to deliver events.

If the situation is symmetrical, both classes can implement the same event interface.


It sounds like what you're looking for is the Observer pattern. The way it works is that observers register with the object that they are observing, such that they can be notified on events.

In your specific case, if you want LocationUpdateHandler to push information to HelloAndroid, it has to know about HelloAndroid. So your LocationUpdateHandler should at least contain a reference to HelloAndroid, but to generalize this, it should have a List of observers that all implement a common interface containing a callback function that would be called whenever LocationUpdateHandler has an update.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜