13

Is it ok to use bindService more than once with the same context to the same service ?

Can I use bindService multiple times with the same context to the same service and unBindService only once ?

Thanks

Anatoly
  • 20,799
  • 3
  • 28
  • 42
refaelos
  • 7,927
  • 7
  • 36
  • 55
  • 2
    As a side note services are singletons in android so you are always going to get back the same service instance when you bind anyway. – ScouseChris Aug 02 '12 at 12:39

3 Answers3

8

It is possible to bind multiply times to the same service with the same context, but it is looks to me as bad practice. Also, you cannot unbind from service only once. You must unbind all your ServiceConnection's .

UPDATE: As for why it looks to me as a bad practice, it is because I can't imagine why one's will need that. Also I think connection wrapper which will bind and unbind only once and serve as facade interface to service could be better, because it'll introduce less overhead and less error prone (in my opinion though)

pepyakin
  • 2,217
  • 19
  • 31
  • Why is binding to the same service multiple times with the same context considered a bad practice? – Vito Andolini May 08 '15 at 03:54
  • @VitoAndolini, it looks like I've used wrong word, it is more like "looks to me" than "considered", sorry about that. I've updated the answer. – pepyakin May 08 '15 at 09:03
  • Thanks for the clarification @pepyakin ! I was wrestling with DeadObjectExceptions from an Android service this week and was trying to figure out the do's and don'ts. – Vito Andolini May 09 '15 at 17:39
  • There are solid reasons to bind to the same service multiple times. For example if multiple activities need a reference to the same service. But if an activity got a service connection, then it should keep it as long as needed and not call bind service again. Also, it must unbind the service in destroy. – Alfred Faltiska Feb 13 '22 at 11:20
3

It doesn't matter how many time you call bindService if you use same context and the service is connected at the moment, android just ignore your call So you can just only bind to a service once with same context and unbind only once

1

When you call bind service the android framework check if the context is bind or not if the context is bind the android just ignore the call