Categories
Windows Phone

Background GPS in a Windows Phone 8.1 Windows Runtime App

In Silverlight 8.0 there was a capability to run an application for a period of time after the user switched away to perform continuous GPS tracking for up to a few hours. With the switch to the Windows Runtime there was no direct equivalent of this. I discovered however that because there are differences with what you are allowed to do on Windows Phone versus Windows Store apps with the DeviceUseTrigger you can do something similar.

The GPS device itself doesn’t qualify for use with the trigger but you can use another sensor on the device. Since all Windows Phone devices have an Accelerometer you can use this. The documentation states that you must poll the sensor at least every 5 seconds otherwise it will kill your background process. Since GPS commonly updates once per second you are given the choice of polling with a 1-5 second interval depending on what you need. With a bit of logic you could extend this but you’d still be polling the accelerometer at least once every 5 seconds.

The GPS adaptation is simply to recreate a DeviceUseTrigger based background task – using the official code sample as a base. Then we add a Geolocator and get the position on each call of the handler which is called for each reading. In the attached sample we simply capture the position every 5 seconds and update the application tile. So you’ll need to run the app and pin it to the start page to see it at work.

In order to show the minimal code to demonstrate the technique I’ve not added any decent error handling or analytics so don’t just paste this code into a real project and use it as-is.

Sample: BackgroundGps.WinRT

By Peter Foot

Microsoft Windows Development MVP