开发者

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

开发者 https://www.devze.com 2023-01-04 15:36 出处:网络
I am following a tutorial to setup a service to start on boot where the last piece of the code is: Make an entry of this service in AndroidManifest.xml as

I am following a tutorial to setup a service to start on boot where the last piece of the code is:

Make an entry of this service in AndroidManifest.xml as

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

Now start this service in the BroadcastReceiver MyStartupInte开发者_JAVA技巧ntReceiver’s onReceive method as

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

}

As you see it uses intent-filters and when starts the service adds action. Can I just use

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

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


Assuming this is all in one application, you can use the latter form (MyService.class).

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

I'd use the custom action string if you wanted third parties to start this service.


As I have already mentioned in the comment, actions may be useful self-testing. E.g., a service performs a lot of tasks. For every task there is an action. If the service is started with an unknown action, an IllegalArgumentException will be thrown.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号