Search code examples
androidandroid-servicelocationmanager

stopSelf in Android service doesn't give a chance for onLocationChanged to fire before exiting


I have setup a service that basically runs every 15 mintues and does a requestLocationUpdates on the GPS provider. I have the listener setup in the service.

Now when the method onStartCommand comes to an end I do a stopSelf as I wish the service to terminate as I know in another 15 minutes it will launch again using the AlarmManager.

But the service quits before the listen event arrives with the location information.

If I comment out the stopSelf that the location is received.

How do I get the service to wait until the location is received. I thought about putting the stopSelf in the event of the onLocationChanged but it may not always fire.

The other way I though of was implementing a thread sleep, but this feels like a code smell.


Solution

  • To get just one location use LocationManager.requestSingleUpdate() and call service.stopSelf() in onLocationChanged(). If you are concerned about the GPS searching for a fix indefinitely (perhaps the user is in a cave), then setup a timer and stop the service when it exceeds your specific period of time.