Thursday, 15 August 2013

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

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

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.
Binding to activity and communicate from fragment to Service via Callback
through the activity? (binding/unbinding in onCreate()/onDestroy())
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!

No comments:

Post a Comment