3

I have a started service that handles a connection and that keep an array of objects. On the other hand, I have a singleton that should bind to that service in order to get one of the objects handled by the service. So, how could I bind the service from the singleton? Is it a good practice to bind the service when the singleton is initialized by using the application's context? Is there a better alternative?

Thanks in advance!

FVod
  • 2,245
  • 5
  • 25
  • 52
  • "Is it a good practice to bind the service when the singleton is initialized ..." I'd consider even having singletons to be bad practice, since you're messing with globals which can (and will) be very difficult to keep track of and debug. Consider this article http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx – Robin Kanters Feb 26 '16 at 10:47
  • @RobinKanters I disagree. While singletons may be generall evil, there are perfectly valid uses for them. Due to the nature of activity lifecycles in Android it is best practice to bind to a `Service` using a long-lived object (like a singleton) instead of binding in each and every `Activity` – David Wasser Feb 26 '16 at 14:34
  • @DavidWasser Yeah, they definitely have their place, I just advice against them because they're usually a bad idea – Robin Kanters Feb 27 '16 at 12:10

1 Answers1

3

This is a perfectly good way to do it. Your singleton gets initialized and binds to the service using application context. The singleton will stay bound until the process hosting your singleton is killed by Android (or until you intentionally unbind). Be aware that if you intentionally unbind then you will need to intentionally bind again if your app starts again before Android has destroyed the hosting process (or you'll need to destroy your singleton so it gets reinitialized later).

In the case where Android kills your process and the user returns to the app, your singleton will get recreated and will rebind to the service.

David Wasser
  • 93,459
  • 16
  • 209
  • 274