Handle geofence notifications from a background task (XAML)

This topic will guide you through the steps of handling Geofence notifications from a background task, in your app.

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

Introduction

After 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 handle a geofence notification when a background task has been triggered. It assumes you have set up a background event listener as described in Listen for geofence events in the background. 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.

Handling the background notification

The action you take to notify the user depends on what your app does but you could possibly display a toast notification, play an audio sound, or update a live tile. The code below handles the notification:

async private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
    if (sender != null)
    {
        // Update the UI with progress reported by the background task
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            try
            {
                // If the background task threw an exception, display the exception in
                // the error text box.
                e.CheckResult();

                // Update the UI with the completion status of the background task
                // The Run method of the background task sets the LocalSettings. 
                var settings = ApplicationData.Current.LocalSettings;

                // get status
                if (settings.Values.ContainsKey("Status"))
                {
                    rootPage.NotifyUser(settings.Values["Status"].ToString(), NotifyType.StatusMessage);
                }

                // do your apps work here

            }
            catch (Exception ex)
            {
                // The background task had an error
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        });
    }
}

Tasks

Set up a geofence

Handle geofence notifications in the foreground

Listen for geofence events in the background

Other resources

Windows 10 geolocation sample

Windows 8.1 geolocation sample

Roadmap for apps using C# and Visual Basic

Roadmap for apps using C++

Designing UX for apps

Guidelines for geofencing

Geoshape

Geofence

Geolocator