Android: Send location data in background periodically (every 30 seconds) and ask server for new data

你说的曾经没有我的故事 提交于 2019-12-21 17:32:00

问题


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;

  1. Location listener with interval of 30 seconds which sets the longitude & latitude values to two local variables
  2. Alarm manager fires pending Intent every 30 seconds to a broadcast receiver.
  3. Broadcast receiver starts an IntentService with location variables in the extras.
  4. The IntentService http posts location and asks for any new data from server.
  5. 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;

  1. 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.

  2. Also, tried firing IntentService directly from alarm manager but could not change PendingIntent extras with the most up-to-date location variables.

Questions;

  1. Is the current implementation the way to go?

  2. Would going down google's GCM route be much more beneficial?

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!