Using GoogleAPIClient in Background Services

2019-06-08 14:37发布

问题:

My scenario is that I would like to have a service periodically obtain some information (eg. location of user), report it to my server and receive a push notification if the location matches some X location.

I would to get some advice on what would be the best mechanism to periodically retrieve location information regardless of whether the application is running or not. Here are the options that I have thought about and some background information on each.

Creating a Standard Android Service

My first thought was to create a STICKY service that initializes a GoogleAPIClient that will get location updates and once a location is received, it will send it to the server. The problem I have with this approach is that I have to periodically get the location information. So the service would be running constantly even if it is not running a location scan. Also what would be the best way to poll for location every so often within a service?

Creating an Alarm with IntentService

The second option I thought about was having the Alarm Manager wake up and start an IntentService which starts location updates (via GoogleAPIClient). Once a location is obtained send to the server and close the location updates. This would solve the issue of periodically starting/stoping location updates. However, I haven't had much luck connecting to GoogleAPIClient within the IntentService without putting a wait and I don't think that is the most efficient thing to do.

Creating a GcmTaskService

This has many advantages of the AlarmManager and seems to be more efficient in terms of doze mode as it only wakes up the Service whenever the phone is in a maintenance mode so it seemed like a good solution. However, I have the same issue as the IntentService which is connecting to a GoogleAPIClient to get location without some sort of wait.

I may be going too far down the rabbit hole on this one and there may be something obvious I am missing so any advice would be great appreciated.

回答1:

I had same problem. I went for the first approach (a sticky service) and everything worked fine. However, I didn't like the fact that the service was always running and visible to the user. That's why I decided to use the JobScheduler API as it's the preferred way of performing background work according to docs.

If your app targets API>=21 then JobScheduler is the way to go. If you want to support older versions of the platform then you should use the recently introduced Firebase JobDispatcher library, which unfortunately lacks of documentation.

Everything is explained here at a Google I/O 2016 presentation. Take a look at it.



回答2:

When you request updates, you can request a maximum frequency. Just use a service and set the maximum frequency equal to the polling interval you want. No AlarmManager needed.