Nikolai Nikolai - 1 month ago 19
Android Question

Strategy pattern and Android Service/UI Messaging communication

I have an Android bound service that communicates with activities with Messenger. My service capture new messages through a handler like this:

@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyService.SEND_BLUETOOTH_MESSAGE:
...;
case MyService.POST_DATA:
...;
case MyService.GET_DATA:
...;
}
}


This was fine at first, but as you can imagine, it quickly became a nasty way too long method. I'd like to refactor this with some fancy Strategy pattern, but I'm a little confused about how to do it. I can't really get rid of those constants since it's the way my activities talk to my service. Any ideas?

Thx in advance

Answer

When you Bind service to your activity you can get instance of the service. That way you can directly call public methods on the instance- and no need of handle message at all.