Geolocation when device goes idle

1.3k Views Asked by At

My appcelerator app on iOS and Android requires getting the latest Geolocation every 5 seconds and sending the location back to a server.

It works well when the app is on and the screen is on, however on both platforms when the screen goes off the geolocation object doesn't appear to get updated very often - so even if I get the geolocation every 5 seconds it's not accurate.

How can I get the geolocation to regularly update when the phone screen is off?

3

There are 3 best solutions below

2
Andrey Danilov On

You should request geolocation in foreground Intent Service in other case it will not work on Android O with 5 seconds accuracy.

Also you should use WakeLock to prevent sleep mode.

2
Jason Priebe On

Do you really want to get the location every 5 seconds while the device is off? That will drain the battery very quickly. I think every 5 to 10 minutes would be more appropriate. And maybe even that is excessive.

If what you really need is regular, periodic updates to position, I would suggest the following two solutions:

  • ios: set Ti.Geolocation.trackSignificantLocationChange to true; if your app was killed by the OS, it will be relaunched on significant location changes; you can detect this situation using the launchOptionsLocationKey of the Ti.App.getArguments()
  • android: implement a background service (https://docs.appcelerator.com/platform/latest/#!/api/Titanium.Android.Service) to check the location

Note: for android, we found that the OS would kill our service periodically, and while it always scheduled it to restart, sometimes, it would schedule that for a very long time out (e.g. 8 hours). We ended up using an AlarmService (https://github.com/benbahrenburg/benCoding.AlarmManager) to periodically launch our background code (e.g. every 30 minutes), and the background code would shut itself down after about 25 minutes.

Also, if you care about your service starting back up after the device is rebooted, you should consider using a BootReceiver (https://github.com/benbahrenburg/benCoding.Android.Tools/) to restart the AlarmService.

Obviously, big props to Ben Bahrenburg for his excellent modules!

0
Eng Wei Chua On

There looks to be an fix coming out for this in 7.2.0

https://jira.appcelerator.org/browse/TIMOB-16066

There's also a 3rd party module that looks to solve the issue also

https://github.com/AppWerft/Ti.LocationUpdatesService

I've yet to try it however