0

The method I have seen for routing intents to their handling methods in an intent service is usually like the following:

 if (action.equals(Constants.INTENT_UPDATE)) {
        handleUpdate(intent);
 } else if(action.equals(Constants.INTENT_UPDATE)) {
        handleUpdate(intent);
 }
 ...

This could be improved slightly by adding a switch statement, but I am wondering if there is a better method for routing intents in an intent service. I come from a Java web background and I am use to either using annotations or having some type of mapping file whereas using if/else blocks is harder to read and grows pretty ugly when you have numerous intents (in my case over 20).

I have also considered this question here on how to map to methods via a Map, though I feel that makes it just more convoluted.

Community
  • 1
  • 1
stevebot
  • 23,275
  • 29
  • 119
  • 181

1 Answers1

1

I would suggest you use the Command pattern. Basically you create a class that implements an interface that has an execute() that the IntentService will call. Make sure that each of the classes that implement Command also implement Parcelable so you can send the Command implementation with the Intent. The idea is to be able to do something like this in your IntentService:

public class MyIntentService extends IntentService {

    public MyIntentService(){
    super("Service Name");
    }

    @Override
    protected void onHandleIntent(Intent intent){
        Command command = (Command)intent.getParcelableExtra("command");
        command.execute();

    }

}
Emmanuel
  • 13,083
  • 4
  • 39
  • 53