0

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

Nikolai
  • 256
  • 2
  • 13
  • Can you make different services depending on functionality? For example Bluetooth service/API service/.. Each of them will have handleMessage, but it wil be coupled by his functionality – X3Btel Oct 25 '16 at 15:31
  • @X3Btel Thx for your answer. That's another issue for which I created a specific [question](http://stackoverflow.com/questions/40241607/several-services-same-android-app). I'd like to do so indeed, but even then I'd have to deal with the same crappy switch, only shorter. – Nikolai Oct 25 '16 at 15:56
  • Im not sure what you dont like about the switch. If every case just calls a method and breaks- it does not look that ugly. If you are using bound service- you can make some methods public and just call it on the service instance – X3Btel Oct 26 '16 at 07:26
  • @X3Btel I'm gonna dig this last comment since I didn't know we could do that – Nikolai Oct 26 '16 at 07:38

1 Answers1

1

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.

X3Btel
  • 1,408
  • 1
  • 13
  • 21