Binding and unbinding Android Service to/from Fragment (in ViewPager)

mauricemoss picture mauricemoss · Aug 15, 2013 · Viewed 7.2k times · Source

I got one single Main-Activity in which I create dynamically Pages inside a ViewPager (via FragmentPagerAdapter). So far so good.

Now I got a Service-Implementation I want that activity/those fragments bind to. And this is the point I ask myself which is the best practice.

  1. Binding to activity and communicate from fragment to Service via Callback through the activity? (binding/unbinding in onCreate()/onDestroy())
  2. Binding to each fragment on creation and unbind when destroyed? (same as above)

Both implementations seem to work. But second one offers straighter communication with service.

When testing the second fragments are bound to service on creation. But when I remove all but one they doesn't seem to be destroyed. When I start to create fragments from that point (only 1 fragment after deleting others) again, binding to service only takes place when I create more fragments than I created before.

Perhaps again for better overview.

  • create activity with one fragment in pager: service connected to fragment
  • create 2 more fragments in pager: service conntected on each creation
  • removing all but one fragment: unbinding seems not to be called
  • create 2 more fragments again: service seems not to be connected
  • create another fragment: service conntected on creation

Is this the behaviour one can expect? Is this the implementation I should choose; obviously straighter communication as on callback-communication?

Thanks for your input in advance!

Answer

WindsurferOak picture WindsurferOak · Aug 15, 2013

I prefer the first method especially if you use a Local Service because you have a handle to your service.

Assume that your activity already has a reference to your Local Service called "MyLocalService" (Checkout the Local Service Example). Then from within your fragment you can easily call something like: getActivity().getMyLocalService(). The good thing about this is that your fragment doesn't have to deal with the lifecycle of the service. Hope this helps.