Linking and disabling an Android service to / from a fragment (in ViewPager)

I have one single main activity in which I dynamically create pages inside the ViewPager (via the FragmentPagerAdapter). So far so good.

Now I got a service implementation. I want this activity / these fragments to bind. And this is the moment that I ask myself, which is the best practice.

  • binding to activity and exchange of information from a fragment to a service through a callback through activity? (binding / decoupling in onCreate () / onDestroy ())
  • Snapping to each fragment to create and untie upon destruction? (as mentioned above)

Both implementations seem to work. But the second offers a more direct connection with the service.

When testing the second fragments are tied to the service at creation. But when I delete everything except one, they don't seem to be destroyed. When I start to create fragments from this point again (only one fragment after deleting the others), the binding to the service occurs only when I create more fragments than I created before.

Perhaps again for a better overview.

  • create activity with a single fragment in a pager: service associated with a fragment
  • create 2 more fragments in the pager: the service associated with each creation.
  • deleting everything except one fragment: the denouement doesn't seem to be called
  • create 2 more fragments again: the service does not seem to be connected.
  • create another fragment: service associated at creation

Can this behavior be expected? Is this the implementation I have to choose; a clearly more direct message, like on a communication callback?

Thanks for your input in advance!

+6
source share
1 answer

I prefer the first method, especially if you are using a local service because you have a handle to your service.

Suppose your activity already has a link to your local service called "MyLocalService" (leave "Local Service Example" ). Then, from within the fragment, you can easily call something like: getActivity (). GetMyLocalService (). It’s good that your fragment does not have to deal with the service life cycle. Hope this helps.

+4
source

Source: https://habr.com/ru/post/951842/


All Articles