Question

I'm quite new to Android development.

When is it a good idea to create an Android Service instead of just using a simple Singleton class?

Take, for example, the data layer downloading information feeds from the internet.

Using a Service seems too much for some cases but sometimes I might need access to a Context so I'm a little unsure about how to design the app.

Was it helpful?

Solution

If it is okay for your process to be killed (along with the singleton) immediately after the user leaves its activities, then use a singleton. If you need it to continue running for some duration after that, use a service. If you would like to continue running after the user leaves it, but can live with it not because the user is now on to something else where memory is needed more, then use a singleton.

The decision between these two only comes down to the lifecycle of your app. For this purpose, that is all a service does -- ask the platform to modify its management of your process. If you need a context in a singleton, just use Context.getApplicationContext() to retrieve the global context for your process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top