Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping and starting a Service based on application state

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, if users keep the application in the background, the Service never stops and drains battery.

I would like the Service to stop when my application is not in the foreground. I was hoping the Application class would let me Override onPause and onResume handlers, but it does not have them. Is there another way I can accomplish this?

like image 832
Andrew Avatar asked Oct 28 '10 16:10

Andrew


1 Answers

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.

like image 188
Pete Doyle Avatar answered Sep 19 '22 16:09

Pete Doyle