Android - bindService more than once
Asked Answered
N

3

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

Newfangled answered 2/8, 2012 at 12:26 Comment(1)
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.Bricklayer
P
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)

Pythoness answered 2/8, 2012 at 12:38 Comment(4)
Why is binding to the same service multiple times with the same context considered a bad practice?Strobe
@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.Pythoness
Thanks for the clarification @Pythoness ! I was wrestling with DeadObjectExceptions from an Android service this week and was trying to figure out the do's and don'ts.Strobe
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.Chockablock
P
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

Parang answered 8/12, 2020 at 17:54 Comment(0)
S
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

Shocking answered 12/1, 2021 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.