启动服务时是否需要添加意图过滤器?
问题描述:
我下面的教程来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>
现在开始在广播接收器MyStartupIntentReceiver的方法的onReceive此服务as
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.wissen.startatboot.MyService");
context.startService(serviceIntent);
}
正如您所看到的,它使用intent-filters,并在启动服务时添加操作。 我可以只用
startService(new Intent(this, MyService.class));
相比其他什么一个优势?
答
假设这是全部在一个应用程序中,您可以使用后一种形式(MyService.class
)。
与其他人相比,它有什么优势?
如果您希望第三方启动此服务,我会使用自定义操作字符串。
答
正如我已经在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);
}