Android background service and AlarmManager

2019-04-14 06:55发布

I am coding an android application that gets the user position every 5 minutes, stores it in the database and sends it to a server.

I have read many ways of doing it, I was going to do the following:

  1. User starts the application
  2. The main UI activity starts a service.
  3. The service runs in background and keeps turning on and off the gps, and creating new threads that will save to database,and send the data to the server.

But I have seen that it can be done with a "Remote service" (http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html) or with an AlarmManager that schedules starting this service every 5 minutes.

The service will need to be running always: it is important that after every interval (5 minutes), it is executed.

I think I need some clarity here.

Thank you for your help,

1条回答
走好不送
2楼-- · 2019-04-14 07:46

I am coding an android application that gets the user position every 5 minutes, stores it in the database and sends it to a server.

Please allow the user to choose the location provider. Not everybody has GPS on their device. Not everybody has GPS enabled. And, not everybody will want the power hit of GPS being turned on every five minutes.

Please allow the user to choose the polling period, including "never poll -- I'll refresh the information manually from the activity". Also, please honor the background data setting (deprecated as of ICS).

I think I need some clarity here.

If the polling is supposed to go on even if the activity is not in the foreground, use AlarmManager. However, most recipes for using AlarmManager will have the real work (in your case, GPS fix and network I/O) be handled by an IntentService. This will not work in your case, because GPS is asynchronous -- you cannot just get a fix whenever you feel like it. It will take a long time, possibly forever, to get a fix, so you have to deal with the delay and eventually timing out the operation. Writing a Service to do this is possible, but tricky, particularly if you are aiming to collect this information even if the device falls asleep.

If, however, the polling is only supposed to go on while the activity is in the foreground and the device is on, I wouldn't bother with a Service at all. Just have the activity use postDelayed() to set up an every-five-minutes scheduled bit of code to run, then have it do the work.

查看更多
登录 后发表回答