如何仅在我的应用程序中没有其他活动运行时停止 Android 服务?

发布于 2024-08-24 16:02:41 字数 322 浏览 2 评论 0原文

有没有办法测试我的应用程序中是否还有其他活动仍然存在?我希望在 onDestroy 方法中停止服务,但只想在堆栈上没有我的应用程序中仍然存在的其他活动时才执行此操作。

我在主活动的 onDestroy() 方法中调用停止服务。这非常有效,除非用户启动我的应用程序,然后在我的应用程序中启动一些活动,然后点击主屏幕并重新启动我的应用程序,他们将破坏我的订单,并且主要活动现在将高于我的应用程序的其他活动。在这种状态下,如果他们点击后退按钮并“退出”我的主屏幕,他们将触发 onDestroy() 方法并终止服务,即使堆栈上还有其他活动打开。我想通过仅当我确定堆栈上没有其他活动打开时才停止服务来避免这种情况。可能的?

Is there a way I can test if there are any other activities in my app still alive? I am looking to stop a service in an onDestroy method, but only want to do this if there are no other activities from my app still alive on the stack.

I have the call stop the service in the main activity's onDestroy() method. This works perfect EXCEPT that if a user launches my app, then launches a few activities in my app, then hits the home screen and RELAUNCHES my app, they will subvert my order and the main activity will now be above other activities of my app. From this state, if they hit the back button and 'back out' of my home screen they will trigger the onDestroy() method and kill the service even though there are other activities open on the stack. I want to avoid this by stopping the service ONLY if I am sure there are no other activities of mine open on the stack. Possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白鸥掠海 2024-08-31 16:02:41

我如何启动一项服务
只要我的任何一个继续运行
应用程序的活动仍在
堆栈,但没有时停止
留下来吗?

不要使用 startService()stopService()。相反,即使您并不真正需要绑定连接,也可以使用 bindService()unbindService()。绑定/取消绑定是引用计数的。如果您使用 BIND_AUTO_CREATE 标志调用 bindService(),则第一个 bindService() 调用将启动您的服务。然后,当所有 bindService() 调用都有匹配的 unbindService() 调用时,Android 将自动关闭您的服务。

How can I launch a service that will
continue to run as long as any of my
app's activities are still on the
stack, yet be stopped when none
remain?

Don't use startService() and stopService(). Instead, use bindService() and unbindService(), even if you don't really need the bound connection. The bind/unbind is reference counted. If you call bindService() with the BIND_AUTO_CREATE flag, the first bindService() call will start your service. Then, when all bindService() calls have had matching unbindService() calls, Android will automatically shut down your service.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文