Usually when I create an Android service I implement the onCreate method, but in my last project this does not work. I tried implementing onStartCommand, and this seems to work.
The question is: when I have to implement a service which method is required? Which methods I have to implement? onCreate, onStartCommand, or both? And what is the role of each?
onCreate()is called when theServiceobject is instantiated (ie: when the service is created). You should do things in this method that you need to do only once (ie: initialize some variables, etc.).onCreate()will only ever be called once per instantiated object.You only need to implement
onCreate()if you actually want/need to initialize something only once.onStartCommand()is called every time a client starts the service usingstartService(Intent intent). This means thatonStartCommand()can get called multiple times. You should do the things in this method that are needed each time a client requests something from your service. This depends a lot on what your service does and how it communicates with the clients (and vice-versa).If you don’t implement
onStartCommand()then you won’t be able to get any information from theIntentthat the client passes toonStartCommand()and your service might not be able to do any useful work.