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.
Finally, Service in Android is a singleton. There is only one instance of each service in the system. It starts on demand and handles all pending Intent s / bound clients. Once it's done or explicitly stopped, it will be destroyed.
In this case, service is a non-singleton nature. It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component. Service is being destroyed along with the component.
Singletons are bad, if you develop them. If you are using dependency injection, let the DI container handle the singleton nature of your Service object. If you are not using dependency injection, use a static method instead of a singleton.
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With