在清单中禁用 Android 服务的目的是什么?

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

在 Android 中,可以通过创建服务的子类来创建服务来执行后台任务等。它为了使用必须在应用程序的清单中指定的服务:

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.

清单中服务的参数之一是 'enabled' 选项:

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

声明禁用服务的目的是什么 - 如果我确实不想要该服务,我就不会首先编写它/将它添加到清单中?

我能看到在清单中禁用服务的唯一用途是,它似乎价值有限,如果它是仅用于调试的服务,我希望在生产中禁用它。我错过了什么吗?

android:enabled 属性设置为资源文件中定义的布尔值。此属性的目的是在不同 Android OS 版本的设备 运行 上启用或禁用服务。

例如,要在 运行 Android 4.3 或更低版本的设备上禁用服务,包括 menifest 属性 android:enabled="@bool/atLeastKitKat"

除了在清单中包含此属性外,您还需要执行以下操作:

res/values/ 下的 bool.xml 资源文件中,添加此行:

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

res/values-v19/ 下的 bool.xml 资源文件中,添加此行:

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

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

Service 的非常特殊的情况下,我同意您很少想要禁用它。一种可能性是插入到系统中的服务(例如,输入法编辑器、辅助功能服务),如果用户在运行时(通过 PackageManagersetComponentEnabledSetting())启用- 解锁功能的应用程序购买。我确信还有其他 Service 场景,尽管 none 在一天中的这个早点突然想到(哈欠!)。

但是,我怀疑 Service "inherits" 它的 android:enabled 设置是 Android 组件类型之一,还有活动、提供者和接收者. android:enabled 的其他场景对于其他组件类型会更常见一些。例如,在您知道需要它之前禁用 BOOT_COMPLETED 接收器被认为是一种很好的形式。因此,例如,如果 BOOT_COMPLETED 接收器仅用于恢复因重启而中断的下载,则仅在进行下载时才需要启用该接收器。在所有其他时间,您最好将其禁用,这样您就不会在 "normal" 重新启动期间浪费用户的时间。