Nouvel Travay
Nouvel Travay

Reputation: 6472

What does Enable flag do for Service

Officially, the Enable flag is for whether or not the Service can be instantiated by the system. But what does that mean in practice? Say I set android:enabled="false”. Does that mean START_STICKY will no longer work? How about START_REDELIVER_INTENT?

Upvotes: 0

Views: 1260

Answers (2)

M.Ed
M.Ed

Reputation: 1328

Setting a service to android:enabled="false" means that no one, not you, and not even the system or any 3rd party app (even if you set android:exported="true"), can start or bind to this service unless you programmatically enable it during certain lifecycles within your application.

It has its use-cases, for example, you might have a service within your app that you don't want any foreign app (be it a system app or a 3rd party app) to start (with startService()) or bind to (with bindService()) unless you allow so.

You might have a service that extends HostApduService, which lets your app to pretend to be an NFC card, and you would only want the system to run your service when an NFC reader device comes in proximity only during certain lifecycles within your app (like only when a specific Activity or Fragment is visible on the screen).

Here are some Kotlin extension functions for starting and stopping such services:

fun Context.runService() {
    val componentName = ComponentName(this, MyService::class.java)
    this.packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)
    this.startService(Intent(this, MyService::class.java))
}

fun Context.killService() {
    this.stopService(Intent(this, MyService::class.java))
    val componentName = ComponentName(this, MyService::class.java)
    this.packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
}

Upvotes: 0

Mike M.
Mike M.

Reputation: 39191

It means the Service will not be created or run at all, regardless of what is returned from the onStartCommand() method, as it will never reach that point.

Just like for an Activity, Service instantiation is handled by the system, so when the documentation indicates that the system cannot instantiate a Service when enabled is false, it means that the Service just will not be run.

Upvotes: 1

Related Questions