绑定服务活动或片段?绑定、片段

2023-09-07 22:40:48 作者:帅逼者`~

我工作的一个音乐播放器应用程序。我有一个具有多个片段,在设备专辑每首歌曲展示睿智,聪明的艺术家等等。结果主要活动我有一个处理所有的播放和其他的东西音乐服务。结果我感到困惑的是我有不同的片段这项服务的结合。结果现在,我的服务和工作pretty多少罚款单独绑定的主要活动和每一个片段。但我在想,如果这真的是最好的做法?有没有什么办法,只是绑定与该服务的主要活动,然后一些如何在其子片段使用它吗?结果我也许缺少活动或碎片或服务的一些很基本的概念。因此,有人请指导我在这方面。结果我想这是更多的是概念上的问题,所以不需要任何code的。但是,如果仍然需要的它,然后请让我知道。

I am working on a music player app. I have a main activity which has multiple fragments, each displaying songs on the device album wise, artist wise etc.. I have a music service which handles all the playback and other stuff. What I'm confused about is the binding of this service with various fragments I have. Right now I'm binding the main activity and each fragment individually with the service and its working pretty much fine. But I was wondering if this is really the best practice? Is there any way to just bind the main activity with the service and then some how use it in its child fragments? I maybe missing some very basic concept of activity or fragments or services. So someone please guide me in this regard. I guess it's more of a conceptual question so any code isn't needed. But still if it's required then please let me know.

编辑:结果我的问题是:什么是绑定与多个子片段(每个将使用该服务)

EDIT : My question is: What would be a better way to bind a service with an activity with multiple child fragments(each of which would be using the service)?

推荐答案

绑定服务来您的活动,而不是片段。您的应用程序的描述,多一个活动片段被换进出,使这个最(真的只),实用的方法。

Bind the Service to your activity and not the Fragment. The description of your application, one activity with multiple Fragment that are swapped in and out, makes this the most (and really only) practical approach.

当你绑定一个服务活动你绑其生命周期到了活动。的见的绑定服务。每次添加或在您的活动,删除片段时间片段创建和销毁。你不想尝试服务链接到这个过程中,因为那时你就必须创建和每次创建或销毁新的片段时破坏的服务。

When you bind a Service to an Activity you are tying its lifecycle to that of the Activity. See Bound Services. Each time you add or remove a Fragment in your activity that Fragment is created and destroyed. You do not want to try to link a service to this process because then you would have to create and destroy the service each time a new fragment is created or destroyed.

而不是绑定到主机活动。然后,您可以用您的主机活动从你的片段进行互动与访问绑定服务的接口或通过意图

Instead bind to the host Activity. You can then interact with your host activity from your fragments with an interface to access the bound service or by Intent.