Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: When to use Service vs Singleton?

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.

like image 589
chakrit Avatar asked Aug 25 '10 15:08

chakrit


1 Answers

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.

like image 184
hackbod Avatar answered Sep 22 '22 23:09

hackbod