What is the purpose of disabling an Android service in the manifest?

2.3k views Asked by At

In Android it is possible to create a Service to do background tasks, etc by creating a subclass of Service. It order to use the Service it must be specified in the manifest for the app:

All services must be represented by elements in the manifest file. Any that are not declared there will not be seen by the system and will never be run.

One of the parameters for a Service in the manifest is the 'enabled' option:

Whether or not the service can be instantiated by the system — "true" if it can be, and "false" if not.

What is the purpose in declaring a Service to be disabled - if I didn't want the Service surely I just wouldn't write it / add it to the manifest in the first place?

The only use I can see for disabling a Service in the manifest, and it seems of limited value, is if it's a Service used only for debugging, and I want it disabled for production. Am I missing something?

2

There are 2 answers

0
Priyank Patel On BEST ANSWER

The android:enabled attribute set to a boolean value defined in a resource file. The purpose of this attribute is to enable or disable the service on devices running on different Android OS version.

For example, to disable the service on devices running Android 4.3 or lower include menifest attribute android:enabled="@bool/atLeastKitKat".

In addition to including this attribute in the manifest, you need to do the following:

In your bool.xml resources file under res/values/, add this line:

<bool name="atLeastKitKat">false</bool>

In your bool.xml resources file under res/values-v19/, add this line:

<bool name="atLeastKitKat">true</bool>
4
CommonsWare On

if I didn't want the Service surely I just wouldn't write it / add it to the manifest in the first place?

In the very specific case of a Service, I agree that it would be rare for you to want to disable it. One possibility would be for a service that plugs into the system (e.g., input method editor, accessibility service) that you only want to enable at runtime (via PackageManager and setComponentEnabledSetting()) if the user make an in-app purchase that unlocks the feature. I am sure that there are other Service scenarios for this, though none are leaping to mind at this early hour of the day (yawn!).

However, I suspect that Service "inherits" its android:enabled setting by virtue of being one of the Android component types, along with activities, providers, and receivers. Other scenarios for android:enabled will be a bit more common with other component types. For example, it is considered good form to have your BOOT_COMPLETED receiver be disabled until you know that you need it. So, for example, if the BOOT_COMPLETED receiver is only used to resume a download interrupted by a reboot, you only need that receiver enabled if you are doing a download. At all other times, you may as well leave it disabled, so you don't waste the user's time during "normal" reboots.