How to stop an Android Service ONLY when there are no other activities in my app running?

前端 未结 1 1432
挽巷
挽巷 2020-12-17 06:08

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

相关标签:
1条回答
  • 2020-12-17 06:40

    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.

    0 讨论(0)
提交回复
热议问题