简体   繁体   English

将片段绑定和解除绑定与片段绑定(在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). 我有一个单一的Main-Activity,我在ViewPager中创建动态Pages(通过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()) (在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 在pager中使用一个片段创建活动:连接到片段的服务
  • create 2 more fragments in pager: service conntected on each creation 在pager中创建2个以上的片段:每个创建都有服务
  • removing all but one fragment: unbinding seems not to be called 除去一个片段之外的所有片段:unbinding似乎没有被调用
  • create 2 more fragments again: service seems not to be connected 再次创建2个片段:服务似乎没有连接
  • 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! 感谢您提前输入!

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 ). 假设您的活动已经引用了名为“MyLocalService”的本地服务 (签出本地服务示例 )。 Then from within your fragment you can easily call something like: getActivity().getMyLocalService(). 然后,从您的片段中,您可以轻松调用类似: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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM