A service (S1) is bound in the constructor of a “plain class” C (i.e. C does not have any lifecycle methods like (onCreate(), onDestroy() etc.) using an Intend. The context is provided on construction time in C’s constructor. C is instantiated by other services (Sx) using themselves as arguments for new C(context). in fact, that is eqivalent to using their respective contexts’ I guess.
Sx1 ->
C -> S1
Sx2 ->
Question is: What’s the best method/location to unbind from S1?
- As there are no lifecycle methods in C, should I create an “artificial” onDestroy() method in C that is called once Sx’s onDestroy method is called? I dislike this a bit because I am lazy and might forget calling the onDestroy() method at some point in time as complexity grows.
- Or could I rely on the fact (don’t know if that really happens) that Android will manage a clean lifecycle and “automatically unbinds” from S1 once Sx or its context is destroyed?
Not really. Sx1 and Sx2 are binding to S1. They are responsible for those bindings. You just happen to have put the
bindService()call in C, for whatever reason.Sx1 and Sx2 have to unbind from S1 when they are done with S1. Whether they unbind themselves or call a method on C to unbind, Sx1 and Sx2 are responsible for the bindings and therefore are responsible for unbinding.