问题
I've got a foreground service (with START_STICKY so no problem for the aspect "killed by OS")that receive a location (GPS) update every 2 seconds for navigation purpose. I don't take any wakelock. My question is: have I to take a wakelock to avoid a deep sleep? Or the location updates is enough to be "running"?
回答1:
After of bit of digging in Android code, the response is: no, you don't need it. Android will grab a wakelock for you (LocationManagerService) until onLocationChange ends or your broadcast receiver receives the intent. If you do some async work (start an intent service, post some code in onLocationChange and so on) then you need to create your own partial wakelock.
回答2:
I am doing the same in an app (but I am using a receiver to receive the locations updates which I recommend - there are many bug reports with the listeners). Your way has 2 problems:
- the service might shut down anyway
- the service will eventually fall asleep - I wonder how come you didn't observe this
The correct way is to register an alarm with the AlarmManager - the alarm will wake a receiver. From onReceive()
you must start a WakefulIntentService which will manage the locks for you.
See:
- PowerManager.PARTIAL_WAKE_LOCK android
- Android design : background long running service or AlarmManager?
EDIT: 2 seconds is really very often. This will kill the battery - expect very low ratings - or bump the interval up.
来源:https://stackoverflow.com/questions/21412791/gps-location-and-deep-sleep