IntentService 中的路由意图

Routing intents in a IntentService

我看到的在意图服务中将意图路由到它们的处理方法的方法通常如下所示:

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

这可以通过添加 switch 语句稍微改进,但我想知道是否有更好的方法在意图服务中路由意图。我来自 Java 网络背景,我习惯于使用注释或具有某种类型的映射文件,而使用 if/else 块更难阅读并且当你有很多意图时变得非常难看(在我的案例超过 20)。

我也考虑过这个问题 here 关于如何通过 Map 映射到方法,尽管我觉得这让它变得更加复杂。

我建议您使用 Command 模式。基本上,您创建一个 class 来实现一个接口,该接口具有 IntentService 将调用的 execute() 。确保实现 Command 的每个 class 也实现了 Parcelable,这样您就可以发送带有 IntentCommand 实现。这个想法是能够在你的 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();

    }

}