Stopping and starting a Service based on application state

后端 未结 8 1519
北海茫月
北海茫月 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:19

    I haven't tested this yet, but it looks like if you use Context#bindService() (instead of Context#startService()), the service should stop when no more activities are bound to it. (see Service lifecycle).

    Then use onPause()/onResume() in each activity to bind/unbind from the service.

    Alternatively, you could add a pair of methods on your service which tell it to start/stop listening for location updates and call it from each activity's onResume()/onPause(). The service would still be running, but the location updates wouldn't be draining the battery.

提交回复
热议问题