Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an android Service a singleton?

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.

like image 560
buckithed Avatar asked Sep 10 '18 17:09

buckithed


People also ask

Are Android service singleton?

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.

Is service a class singleton?

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.

Should service be singleton Java?

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.

What is a singleton in software?

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.


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

like image 173
TheWanderer Avatar answered Nov 10 '22 14:11

TheWanderer


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.

like image 40
ygngy Avatar answered Nov 10 '22 15:11

ygngy