What is the best way to keep user’s location in sync with server,even after the app is terminated?
here is what I found this far
- using a foreground service. I already tested that but it’s battery consuming, and sometimes it’s killed when you lock the phone or turn off the screen.
- using work manager. I also tested it, it sends the location every 15 mins,but so unreliable, and it stopped sending after a while.
- Geofencing. I read that Geofencing api gets location updates more often, every couple of minutes or so, but I haven’t tested it.
- LocationListener. There is a method called onLocationChanged, but I don’t know how would it work in background.
is there something like a broadcast receiver that will be fired only when location changed by a margin? I think this would be an optimized solution.
I am building an app that uses a feature similar to facebook nearby friends (which is stopped working long time ago) or something like tinder to display nearby people.
Currently I need this for android, but I will need it for IOS as well, I am developing a flutter app.
2
Answers
As discussed in the comments above, I don’t really think Android allows for you to get location updates in the background even when the application is not active.
I recommend you instead try to query for location as soon as the app starts, and quickly follow up with whatever actions you need to make with it. As an option, you can also keep track of location history by caching their location as they interact with the app, in case you want to keep the database as fresh as possible.
Here’s some pseudo code as a simple example:
I already used a similar method in my app which is working:
I used foreground service to record the location, the battery consumptions are related to the frequency of location request not really the foreground service itself. indeed using LocationListener is a good option
then I am checking the foreground service regularly using workmanager and restart it when needed.
best