Bamadeva
Bamadeva

Reputation: 335

why onStartCommand() is used in Service?

I'm a bit confusion using service where I do implement onStartCommand(). In some example onStartcommand() method is implemented and somewhere not. For what I need to use this method can u please clarify my doubt.

Upvotes: 2

Views: 3635

Answers (4)

Deeptha Deepu
Deeptha Deepu

Reputation: 1

you should implement the onStartCommand() method in your service when you want to define the behavior of your service when it's started and when you want to control how it should behave when restarted or if it's killed by the system. If your service doesn't require custom behavior on start or restart, you can omit this method, and the default behavior will be applied based on the service's return value.

Upvotes: 0

waqaslam
waqaslam

Reputation: 68187

onStartCommand is used to pass on commands (intent) to service. It can be called as many times as you want. However, onCreate is called only once, guaranteeing that the service is created.

Upvotes: 1

Lukas Batteau
Lukas Batteau

Reputation: 2483

The onStartCommand() is called when you start the service using the startService() method. You never start the service yourself, but request that the given service is started, using an intent.

Some examples use the bindService() method instead of the startService() method (you can also use both). A bound service runs only as long as another application component is bound to it.

Usually, a started service performs a single operation and does not return a result to the caller.

Upvotes: 1

Andy Res
Andy Res

Reputation: 16043

The Android documentation says that onStartCommand() is:

Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly

Upvotes: 2

Related Questions