问题
Scenario:
Post to server to get any new data in background every 30 seconds for long period i.e. 12 hours. Location data needs to be sent along with this.
Current Implementation;
Service Class;
- Location listener with interval of 30 seconds which sets the longitude & latitude values to two local variables
- Alarm manager fires pending Intent every 30 seconds to a broadcast receiver.
- Broadcast receiver starts an IntentService with location variables in the extras.
- The IntentService http posts location and asks for any new data from server.
IntentService send server response back to main service class via broadcast receiver.
- Service class starts_sticky to ensure restart by the OS.
I have tried a few different variations;
I've tried using a Handler and runnable to handle the timing mechanism for posting to the server however, the postDelay time went from 2 minutes to 7 minutes when device is asleep.
Also, tried firing IntentService directly from alarm manager but could not change PendingIntent extras with the most up-to-date location variables.
Questions;
Is the current implementation the way to go?
Would going down google's GCM route be much more beneficial?
How can you vigorously test the service class especially with respect to recovering from the OS killing it?
Thanks in advance.
回答1:
To avoid the OS to kill your service, you must notify the user that your service is an ongoing service, like described in http://developer.android.com/guide/components/services.html#Foreground.
I managed to have my service running every 2 min at background using AlarmManager and WakeLock, like described in this answer. Even when the device is sleep, it runs every 2 minutes. Just set the Alarm to repeat like
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+5000, 60000 * ALARM_PERIOD_IN_MINUTES, alarmPendingIntent);
instead of setting it to a time.
来源:https://stackoverflow.com/questions/15903877/android-send-location-data-in-background-periodically-every-30-seconds-and-as