Listen for geofence events in the background (HTML)

This topic will guide you through the steps of setting up a background task to listen for Geofence notifications in your app.

Roadmap: How does this topic relate to others? See:

Introduction

Once your geofences have been created, you will have to add the logic to handle what happens when a geofence event occurs. Depending on the MonitoredStates that you have set up, you may receive an event when:

  • The user has entered a region of interest.
  • The user has left a region of interest.
  • The geofence has expired or been removed. Note that a background app is not activated for a removal event.

This topic describes how to set up a background task to alert your app when a geofence event occurs. But you can also handle events directly from your app when it is running. For more info, see Handle geofence notifications in the foreground and Guidelines for geofencing.

Listening for a geofence event in the background requires a number of steps:

  • Declaring the background task in your app’s manifest
  • Register the background task in your app. If you app needs internet access, say for accessing a cloud service, when the event is triggered, you can set a flag for that. You can also set a flag to make sure the user is present when the event is triggered so that you are sure the user gets notified.
  • While your app is running in the foreground, prompt the user to grant your app location permissions.

Register for geofence state change events

In your app's manifest, under the Declarations tab, add a declaration for a location background task. To do this:

  • Add a declaration of type Background Tasks.
  • Set a property task type of Location.
  • Set an entry point into your app to call when the event is triggered.

Register the background task

The code below registers the geofencing background task. Remember that when the geofence was created, we checked for location permissions. Refer to Set up a geofence for more information.

function registerBackgroundTask() {
    try {
        // Request lockscreen access
        Background.BackgroundExecutionManager.requestAccessAsync().done(
            function (backgroundAccessStatus) {
                var builder =  new Windows.ApplicationModel.Background.BackgroundTaskBuilder();

                // Register the background task
                builder.name = sampleBackgroundTaskName;
                builder.taskEntryPoint = sampleBackgroundTaskEntryPoint;
                builder.setTrigger(new Windows.ApplicationModel.Background.LocationTrigger(Windows.ApplicationModel.Background.LocationTriggerType.geofence));

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                // var condition = new SystemCondition(SystemConditionType.userPresent | SystemConditionType.internetAvailable);
                // builder.addCondition(condition);

                geofenceTask = builder.register();

                geofenceTask.addEventListener("completed", onCompleted);

                LocationTriggerBackgroundTask.updateButtonStates(/*registered:*/ true);

                switch (backgroundAccessStatus) {
                    case Background.BackgroundAccessStatus.unspecified:
                    case Background.BackgroundAccessStatus.denied:
                        WinJS.log && WinJS.log("This app is not allowed to run in the background.", "sample", "status");
                        break;

                    default:
                        // Finish by getting an initial position. This will present the location consent
                        // dialog if it's the first attempt for this application to access location.
                        getGeopositionAsync();
                        break;
                }
            },
            function (e) {
                // Did you forget to do the background task declaration in the package manifest?
                WinJS.log && WinJS.log(e.toString(), "sample", "error");
            }
        );
    } catch (ex) {
        // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) === -2147024846

        if (ex.number === -2147024846) {
            WinJS.log && WinJS.log("Location Simulator not supported.  Could not get permission to add application to the lock screen, this application must be added to the lock screen before the background task will run.", "sample", "status");
        } else {
            WinJS.log && WinJS.log(ex.toString(), "sample", "error");
        }
    }
}

Roadmaps

Roadmap for apps using JavaScript

Designing UX for apps

Tasks

Set up a geofence

Handle geofence notifications in the foreground

Handle geofence notifications from a background task

Reference

Geoshape

Geofence

Geolocator

Other resources

Windows 10 geolocation sample

Windows 8.1 geolocation sample

Guidelines for geofencing