Is an android Service a singleton?

Viewed 1754

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().

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.

Related