For my App I need to use service discovery. Service Discovery is a piece of code that lets your android device search for other devices in the same network that can connect to you. But also it gives you the power to generate your own service so other devices can find you.
I wont go into detail about how to setup all this but it involves a lot of callback listeners. Althrough I like the idea of this I dont like the way some people on the internet, who explain this to people who never done this before, implement it. As stated in my previous android blogpost the standard tutorials work with the idea of putting everything in a activity. And well I just dont like that.
So for the service discovery logic and all listeners (3!) that go with it I created a class called ServiceHelper ( if you take a look at the tutorials from android about service discovery they use the same idea ). This helper is a singleton that registers a certain service on the network and works as its own listener for these type of events. So how is this different from the default approach?
The difference comes when I want to let the activity know that something has happened. I’m using the so called Observer/Observable pattern for this. I create my activity. I retrieve an instance of my servicehelper and add myself as a listener to that helper class.
the only thing I need to do next is to add a method ‘update’ so the helper can inform me about what happened. Why I like this idea better? Simple. If an activity implements a RegisterServiceListener, a ResolveListener, a GetMeSomeCoffeeListener the activity gets poluted with all kinds of ‘listener’ methods such as ‘onCoffeeServed’ or ‘onNoCoffeeAnymore’ methods.
Now I only have 1 method update(source, data) and in this update method I can add the logic to handle all the events I’m interested in. I think it makes the code a bit cleaner and easier to understand.