Stopping and starting a Service based on application state

后端 未结 8 1460
北海茫月
北海茫月 2021-01-05 16:45

I have a Service which tracks the location of the user. Currently, the Service boots when the application starts and stops when the application terminates. Unfortunately,

相关标签:
8条回答
  • 2021-01-05 17:21

    It sounds like the real problem is how to only stop the service when you go to an activity that isn't one of your own? One way would be to in your onPause method to stop the activity. Do this for all your activities. Then override your startActivity method. And in here do a conditional test to confirm that you are purposefully navigating to one of your own. If your are set a flag to true.

    Now go back to your on pause overridden method. And only stop your service if the flag is not equal to true. Set the flag to false.

    All events that navigate away will close your service. Navigating to your own will leave it intact.

    Do the overriding in a base class that all your activities extend.

    Writeen in my andolroid. Will post ezaple later.

    0 讨论(0)
  • 2021-01-05 17:23

    Try using the Bound Services technique to accomplish this.

    Bound Services | Android Developers

    You can use bound services in a way such that the service will stop when no activities are bound to it. This way, when the app is not in the foreground, the service will not be running. When the user brings the app back to the foreground, the Activity will bind to the service and the service will resume.

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