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

2023-09-04 23:47:45 作者:◆◇℡敷衍不嘚的爱丶

有没有一种方法,我可以测试是否有我的应用程序的任何其他活动还活着吗?我期待停在的onDestroy方法的服务,而只是想这样做,如果有从我的应用程序没有其他活动还活着,在堆栈中。

我的电话停在主要活动的的onDestroy()方法的服务。这完美的作品只是如果用户启动我的应用程序,然后在我的应用程序推出一些活动,然后点击主屏幕,并重新推出我的应用程序,它们会颠覆我的订单,现在的主要活动将高于我的应用程序的其他活动。从这种状态,如果他们打后退按钮和'回退'我的主屏幕,他们将触发的onDestroy()方法,并杀死即使有堆栈上打开其他活动的服务。我想通过停止只有当我相信有我的任何其他活动堆栈上打开的服务,以避免这种情况。可能吗?

解决方案   

我怎么能推出一项服务,   继续下去,只要任何一个运行我   应用程序的活动仍然在   栈,但被停止时,没有   留?

不要使用 startService() stopService()。相反,使用 bindService() unbindService(),即使你并不真的需要绑定的连接。绑定/解除绑定的引用计数。如果你调用 bindService() BIND_AUTO_CREATE 标记,第1 bindService()通话将开始为您服务。然后,当所有的 bindService()通话有匹配 unbindService()电话,Android将自动关闭你的服务。

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?

解决方案 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.