6

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!

mauricemoss
  • 150
  • 3
  • 9
  • 3
    I have built similar scenario using your first approach (activity manage communication to service) and it worked out pretty well. This allow me to share the service connection across all fragments and allow fragment "more" immediate access to service (without having to deal with the async of bind) – Phuong Nguyen Aug 15 '13 at 21:26

1 Answers1

4

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.

WindsurferOak
  • 4,861
  • 1
  • 31
  • 36
  • 1
    Yep, helps! ;) Think my thoughts were little to complicated. Providing service via some getActivity().getMyService() will do the trick and prevent from possible mentioned errors with async binding. – mauricemoss Aug 16 '13 at 16:59