gpt4 book ai didi

android - 绑定(bind)到 Android 中的服务

转载 作者:搜寻专家 更新时间:2023-11-01 08:17:08 26 4
gpt4 key购买 nike

我对服务绑定(bind)的工作原理有点困惑。我了解使用 Context.startService() 启动服务并且 bindService 不会调用 onStartCommand。但我的理解是,如果我使用 startService,我必须明确停止该服务。但是如果没有更多的 Activity 绑定(bind)到它,我希望服务终止。

我的问题是调用 bindService 永远不会调用 onServiceConnected(),所以我的服务绑定(bind)器对象是空的。服务是否必须显式启动才能绑定(bind)到它?如果是这样,当没有任何东西再绑定(bind)到它时它如何知道终止,我如何知道它是否已启动以便我知道使用绑定(bind)对象?

最佳答案

如果您使用 BIND_AUTO_CREATE 作为标志调用 bindService,如果该服务存在,系统会将您的 Activity 绑定(bind)到该服务,否则,如果它不存在,系统将为您启动该服务,然后它将将您的 Activity 绑定(bind)到服务。此外,如果您以这种方式启动服务,该服务将仅在它仍然绑定(bind)了一些上下文时才会保持 Activity 状态。

这是来自 bindService():

Connect to an application service, creating it if needed. This defines a dependency between your application and the service. The given conn will receive the service object when its created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed

这是来自 ServiceLyfecycle

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

关于android - 绑定(bind)到 Android 中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3163280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com