Skip to content Skip to sidebar Skip to footer

What Can I Expect When Oncreate() Calls Startservice()

I am trying to understand the Service Life Cycle while working through some Android Open Source Code. I was looking at a Service implementation which I distilled down to something

Solution 1:

You are correct in that a Service will call onCreate and onStartCommand if it is started via Context.startService. So in this sense, when you return START_STICKY, the Service will continually run until an explicit call to stopService() is called. It will also be destroyed and restarted during this lifecycle.

Another way to create a Service, is by binding to it. As per the docs:

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand().

So, it's possible for a Service to be created by simply binding to it. However, the lifecycle of a Service indicates that it will remain if it is started or a client is still bound to it. Meaning, that if it was created by a bind command, it will immediately be destroyed as soon as the client unbinds.

So, if a Service starts itself in the onCreate(), it will ensure that it puts itself in the started state regardless of whether it was created by binding or by an explicit call to startService. Since there's no actionable intent, the onStartCommand will just pass straight through. An clients that call startSevice will, presumably, have actionable Intents in which case the Service will perform its duties.

Post a Comment for "What Can I Expect When Oncreate() Calls Startservice()"