[英]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. 这就是我要问自己哪一点是最好的做法。
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. 也许再次提供更好的概述。
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.