Anjani Anjani - 1 year ago 726
Android Question

Bind service to activity or fragment?

I am working on a music player app. I have a main activity which has multiple fragments, each displaying songs on the device album wise, artist wise etc..

I have a music service which handles all the playback and other stuff.

What I'm confused about is the binding of this service with various fragments I have.

Right now I'm binding the main activity and each fragment individually with the service and its working pretty much fine. But I was wondering if this is really the best practice? Is there any way to just bind the main activity with the service and then some how use it in its child fragments?

I maybe missing some very basic concept of activity or fragments or services. So someone please guide me in this regard.

I guess it's more of a conceptual question so any code isn't needed. But still if it's required then please let me know.


My question is: What would be a better way to bind a service with an activity with multiple child fragments(each of which would be using the service)?

Answer Source

Bind the Service to your activity and not the Fragment. The description of your application, one activity with multiple Fragment that are swapped in and out, makes this the most (and really only) practical approach.

When you bind a Service to an Activity you are tying its lifecycle to that of the Activity. See Bound Services. Each time you add or remove a Fragment in your activity that Fragment is created and destroyed. You do not want to try to link a service to this process because then you would have to create and destroy the service each time a new fragment is created or destroyed.

Instead bind to the host Activity. You can then interact with your host activity from your fragments with an interface to access the bound service or by Intent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download