Does overriding Service.OnStartCommand put the service into the started state?

Issue

In the bound services documentation, it says

When a service is unbound from all clients, the Android system destroys it (unless it was also started with a startService() call). As such, you don’t have to manage the lifecycle of your service if it’s purely a bound service—the Android system manages it for you based on whether it is bound to any clients.
However, if you choose to implement the onStartCommand() callback method, then you must explicitly stop the service, because the service is now considered to be started. In this case, the service runs until the service stops itself with stopSelf() or another component calls stopService(), regardless of whether it is bound to any clients.

Does this mean that simply implementing onStartCommand automagically puts the service into a started state when a client binds to it?

I’ve been looking for a way to guarentee that when a client binds to the service, the service is in the started state. So far, the only way I’ve been able to do it is by having the client call startService followed by bindService. But if the above is correct, then all I have to do is implement onStartCommand and the client is free to just call bindService.

Solution

I agree that the documentation is wrong. Simply implementing onStartCommand() changes nothing. Especially because you don’t implement it, you override the method, because there is already an existing default implementation of onStartCommand()

When you bind to a Service, the Service isn’t technically "started", it is just bound. onStartCommand() will not be called unless something calls startService().

Answered By – David Wasser

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published