假设Activity A启动Service S并绑定(bind)到Service S。
当 A 被销毁时,S 会发生什么?
如何重新创建绑定(bind)到 S 的另一个 Activity? http://developer.android.com/guide/components/bound-services.html中的示例代码在 onStop() 中取消绑定(bind)服务。我想如果我再次打开该应用程序,则会为 A 和 S 的另一个实例创建一个新进程。但我希望新 Activity 从旧服务获取数据。
最佳答案
What will happen to S when A is destroyed?
如果 A 是绑定(bind)到 S 的唯一 Activity,并且您没有通过 startService(Intent)
启动服务,S 将被销毁。那是因为服务将一直存在,直到最后一个绑定(bind)的 Activity 与服务解除绑定(bind)。这记录在案 here .
How can I recreate another Activity that binds to S?
如果A被绑定(bind),你通过Intent切换到Activity B,当B绑定(bind)到它时,Service将被销毁并重新创建。
如果您希望服务在没有 Activity 绑定(bind)的情况下仍然存在,您必须使用 startService(Intent)
调用服务。现在,如果您明确停止它或系统意味着是时候销毁它,它就会存在。如果您不想要这种行为,请保留您的数据并在给定时间访问它。
I think if I open the app again, a new process is created for another instance of A and S
进程保持不变,直到进程从系统中终止,或者如果您终止进程,不推荐这样做。
编辑:
只有绑定(bind)的服务生命周期依赖于 Activity 。如果您想要一个独立的,请使用 startService()
。这样它就独立于 Activity 并在后台运行,只要应用程序的进程启动或您使用 stopService()/stopSelf()
显式停止服务。您甚至可以在自己的应用程序中拥有一个服务,并使用 IPC 在应用程序之间进行通信。这完全取决于用例。
如您所见,服务的配置非常灵活,您必须决定哪种最适合您的应用。
关于安卓服务 : What happen at the end of Activity life?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18779610/