If I start a service in my main activity, then exit main and create main again, will a new service instance be put in its place? or will it be the same instance? or will there be two instances? I need to know because in my service I make a unique id for every time a new service is created.
2 Answers
Whenever you call startService()
or startForegroundService()
in Android, the framework checks if that Service is already running.
So to answer your question, yes. There will only be a single instance.
However, every time you call startService()
or startForegroundService()
, the Service's onStartCommand()
method will be called. That means, if you have any one-time initialization in your Service that you don't want to be reinitalized, put it in onCreate()
.

- 16,775
- 6
- 49
- 63
-
@AnubhavGupta this answer is not totally correct because service may stop after it is started. – ygngy Sep 10 '18 at 18:35
-
@BAHMAN but that wasn't the question. – TheWanderer Sep 10 '18 at 18:36
-
2@TheWanderer the question was about creating new ides at service creation. service may stops and new id may creates and it has worth to know. – ygngy Sep 10 '18 at 18:38
-
1@BAHMAN thank you for pointing that out. In this case I'll just save the id in shared pref's the first time it is created, and retrieve the id every other time. – buckithed Sep 10 '18 at 18:48
If I start a service in my main activity, then exit main and create main again, will a new service instance be put in its place?
You have two situations If your service remains running a new instance will not be created but if your service stops (ends its work or system stops it due to low memory or other situations) when you start it again you get a new instance of it.

- 3,630
- 2
- 18
- 29