123

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?

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
GVillani82
  • 17,196
  • 30
  • 105
  • 172

2 Answers2

213

onCreate() is called when the Service object 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 using startService(Intent intent). This means that onStartCommand() 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 the Intent that the client passes to onStartCommand() and your service might not be able to do any useful work.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • 7
    Can two instances of the same Service exist within an application? – jacktrades May 30 '13 at 11:44
  • 1
    @jacktrades Theoretically and according to the documentation: No. However, there seems to be some bug in Android where indeed in certain circumstances it will create multiple instances of a Service. However, as I said, this is a bug, and we have not been able to reliably reproduce it at will. Why are you asking? – David Wasser May 30 '13 at 21:01
  • Wasse ok. Because if there are 2 instances the onCreate() would be called twice. – jacktrades May 31 '13 at 13:12
  • @DavidWasser: did not manage to find any report for this bug (apart from things like :https://groups.google.com/forum/#!topic/android-developers/3Ngxwy8Gva4) - do you have any links on this ? Also the service docs do not clearly state that the service is indeed a singleton - where is this stated clearly ? Just trying to fully grok this – Mr_and_Mrs_D Nov 18 '13 at 21:58
  • 3
    @Mr_and_Mrs_D There are no official bugs reported as far as I know. However, there are several reports of this happening and I have an application where I know that it is happening. I have been unable to reduce the problem to something small and repeatable so I have not filed a bug myself. The documentation does not explicitly state that services are singletons, but it is very clear that that is what is intended. Look at the docs for 'startService()`: clearly states that _if the service is not already running, it will be created and started, if it is running it remains running_ – David Wasser Nov 18 '13 at 22:56
  • As far as I can tell, onStartCommand should be called onRequestServiceToDoSomething. onCreate makes sense though. – Carlos Nov 22 '13 at 08:42
  • So, if stopSelf() is called, and after startService() is called, is onCreate() called? What happens when the process dies? It seems that onCreate() is called even if it appears as "0 process, 1 service" from Settings -> App – Angelo Mar 12 '14 at 15:24
  • If `stopSelf()` is called then the `Service` stops and the `Service` object is dead (can be garbage collected). If, after that, `startService()` is called, then a new instance (a new object) is created and `onCreate()` is called on that new instance. I don't know exactly how the values for the display in Settings->App are obtained. – David Wasser Mar 12 '14 at 16:12
  • So when i call a service using startService(intent), will onCreate() wont be called? I have a doubt understanding what is a 'service object' because i have always started a service by startSevice(intent). – Diffy Oct 25 '14 at 07:38
  • 8
    @Diffy When you call `startService()`, if the service is not running, Android will create an instance of the service class (this is a service object) and will then call `onCreate()` on that object. It will then call `onStartCommand()` on that object. If, some time later, you again call `startService()`, if the service is still running, Android will not create a new service object. Instead, it will just call `onStartCommand()` on the existing service object. Is that clear? – David Wasser Oct 25 '14 at 22:06
  • 'Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand())' as per http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle Would you want to correct your answer? – Vedant Agarwala Jul 28 '15 at 12:45
  • @vedant1811 What do you think in my answer needs correcting? The answer is completely correct. Perhaps you misunderstand what "nesting" means? – David Wasser Jul 28 '15 at 18:23
  • @DavidWasser your last line in the answer was dreadful. I want to create a service that just checks any change in content of clipboard, all the time. And I feel of not using onStartCommand() at all. Wont that be okay? – Srujan Barai Nov 10 '15 at 18:20
  • @SrujanBarai sorry, I don't understand your problem. Perhaps you should post a new question and explain your problem, instead of tacking a comment on to an existing question. Posting new questions doesn't cost anything ;-) – David Wasser Nov 11 '15 at 18:53
  • 1
    So after knowing this, where should I call `startForeground()`? On `onCreate()` or on `onStartCommand()`? (And why?) Still, thank you very much for the explanation! – Edw590 May 07 '21 at 18:40
  • 1
    @DADi590 you can call `startForeground()` in either place. If your app needs to run in the foreground all the time you can call it in `onCreate()`. If your service only needs to run in the foreground in certain circumstances, you can decide this in `onStartCommand()` or later and call it then. – David Wasser May 07 '21 at 19:30
  • Just want to add here, that interacting to the service via `android.content.Context#bindService` only calls the `onCreate` but not `onStartCommand`. – daparic Aug 24 '22 at 05:55
14

Service behave same like Activity Whatever you want to associate once with a service will go in onCreate like initialization

and whenever the service is called using startService. onStartCommand will be called. and you can pass any action to perform . like for a music player , You can play ,pause,stop using action

And you do any operation in service by sending an action and receiving it on onStartCommand

onCreate work like a Constructor.

Edit in Short

onCreate() calls only for the first time you start a Service Whereas onStartCommand() calls everytime you call the startService again. It let you set an action like play,stop,pause music.

public void onStartCommand()
{
     if(intent.getAction.equals("any.play")
     {
        //play song
     }
     else if(intent.getAction.equals("any.stop")
     {}
}
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
  • So when i call a service using startService(intent), will onCreate() wont be called? I have a doubt understanding what is a 'service object' because i have always started a service by startSevice(intent). – Diffy Oct 25 '14 at 07:38
  • have you properly instantiate the service object or Probably you don't have the service in your manifest – Zar E Ahmer Oct 25 '14 at 07:44
  • start service like startService(new Intent(this, ServiceName.class)); – Zar E Ahmer Oct 25 '14 at 07:44
  • But is this method called instantiating the service? Where is the service-object then? – Diffy Oct 25 '14 at 08:06
  • it is a way of calling Activity and Service using intent is responsible for opening Activity and Service in Android. What you want to do with object of service you can also do it with intent. i mean passing data to Service – Zar E Ahmer Oct 25 '14 at 10:02
  • Intent is basically a message that is passed between components (such as Activities, Services, Broadcast Receivers, and Content Providers). An Intent is an "intention" to do an action.Intent is an interface to allow transtion or starting services in Android platform. An Intent is an object that provides runtime binding between separate components – Zar E Ahmer Oct 25 '14 at 10:12
  • If you want to execute manually some method on the Service class or get some data or some object from that Service then you need to bind to the service. Android Developers explains how to do that. – Joaquin Iurchuk Feb 18 '15 at 13:08
  • If a service is restarted by Android, does it call onCreate again? – daparic Sep 17 '21 at 22:00