Difference between onStartCommand() and onBind()
onStartCommand() and onBind() are callback methods of Service class.
onStartCommand()
called after onCreate()
method of Service class first time.Next time whenever any other android component start same service then Service received new request in onStartCommand()
method.
onBind()
called when another Android components try to connect with already running Service by using bindService()
method .Its used to pass some new info to service or try to make Service connection.
A bound service will end when it has no more activities bound to it. Binding also allows you to send additional commands to it via interfaces like AIDL
. In your case, I think you'd want a bound service, as you likely don't want the service to outlive the activity.
The first (onStartCommand()
) is called when your Service
begins to do its work. onCreate()
has completed and it is ready to get to doing what needs to be done.
The second (onBind()
) is called when another Thread registers to connect to the Service so that they can communicate. You would configure or set up the means for the communication in here such as Interface validation or calls back to the registering Activity.
Binding allows you to tie the Service to the lifespan of, for example, an Activity. If the Activity completes then the Service is allowed to be released and can itself finish. The Service will last as long as there is something still bound to it.