【问题标题】:Do I need to add an intent-filter when starting a service?启动服务时是否需要添加意图过滤器?
【发布时间】:2010-06-25 21:47:17
【问题描述】:

我正在关注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>

现在在 BroadcastReceiver MyStartupIntentReceiver 的 onReceive 方法中启动这个服务

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));

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

【问题讨论】:

    标签: android service intentfilter


    【解决方案1】:

    假设这一切都在一个应用程序中,您可以使用后一种形式 (MyService.class)。

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

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

    【讨论】:

      【解决方案2】:

      正如我在comment 中已经提到的,操作可能是有用的自我测试。例如,服务执行很多任务。每个任务都有一个动作。如果服务以未知操作启动,则会抛出IllegalArgumentException

      我通常在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);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 2023-04-03
        • 1970-01-01
        • 2019-07-25
        • 1970-01-01
        • 1970-01-01
        • 2011-02-15
        • 2011-11-07
        • 1970-01-01
        相关资源
        最近更新 更多