代码之家  ›  专栏  ›  技术社区  ›  Pentium10

Do I need to add an intent-filter when starting a service?

  •  6
  • Pentium10  · 技术社区  · 14 年前

    我正在遵循一个教程 setup a service to start on boot 最后一段代码是:

    在AndroidManifest.xml中输入这个服务

    <service android:name="MyService">
    <intent-filter>
    <action
    android:name="com.wissen.startatboot.MyService" />
    </intent-filter>
    </service>
    

    Now start this service in the BroadcastReceiver MyStartupIntentReceiver’s onReceive method as

    public void onReceive(Context context, Intent intent) {
        Intent serviceIntent = new Intent();
        serviceIntent.setAction("com.wissen.startatboot.MyService");
        context.startService(serviceIntent);
    
    }
    

    正如您所看到的,它使用意图过滤器,当服务启动时,添加动作。 我可以用吗?

    startService(new Intent(this, MyService.class));
    

    What's the advantage of one compared to the other?

    2 回复  |  直到 14 年前
        1
  •  7
  •   CommonsWare    14 年前

    假设所有这些都在一个应用程序中,则可以使用后者的形式( MyService.class )

    一个与另一个相比有什么优势?

    如果您希望第三方启动此服务,我将使用自定义操作字符串。

        2
  •  0
  •   Community CDub    7 年前

    正如我已经提到的 comment IllegalArgumentException 将被抛出。

    I usually use this approach in onStartCommand .

    String action = intent.getAction();
    if (action.equals(ACT_1)) { 
        // Do task #1
    } else if (action.equals(ACT_2)) {
        // Do task #2
    } else { 
        throw IllegalArgumentException("Illegal action " + action);
    }