title: Geofence in the Background Windows Phone 8.1 (WinRT)
body: <h2>Issue</h2>
  
  <p>I'm trying to trigger a BackgroundTask when a Geofence Event (Enter / Exit) occurs in WP8.1 (WinRT). I've written a sample application to try to get it working, but can't seem to be able to do so.</p>
  
  <p>So far, these are the steps I've taken to try to get Geofences working in the background:</p>
  
  <ol>
  <li>Check for Location Capabilities</li>
  <li>Create + Register a Geofence</li>
  <li>Create + Register a BackgroundTask that listens for <code>LocationTrigger(LocationTriggerType.Geofence);</code></li>
  <li>In my background task, trigger a simple popup notification</li>
  </ol>
  
  <h2>Things I have done to Troubleshoot</h2>
  
  <p>I have enabled in my app.manifest:</p>
  
  <ul>
  <li>Toast Capable => Yes</li>
  <li>Capabilities: Location, Internet(Client &amp;
  Server)</li>
  <li>Declarations: BackgroundTasks (Location). EntryPoint = <code>BackgroundTask.GeofenceBackgroundTask</code></li>
  </ul>
  
  <p>My background task is located in a separate project, titled <code>BackgroundTask</code>. It is a WindowsRT Component and contains one class <code>GeofenceBackgroundTask</code>.</p>
  
  <p><img src="https://i.stack.imgur.com/nOLZK.png" alt="Project Layout"></p>
  
  <h2>Sample Project</h2>
  
  <p>The code for the project can be found at this <strong>[link]</strong>(<a href="https://github.com/kiangtengl/GeofenceSample" rel="noreferrer">https://github.com/kiangtengl/GeofenceSample</a>):</p>
  
  <h2>How To Test</h2>
  
  <ol>
  <li><p>Run the code in the emulator</p></li>
  <li><p>Set Location to to: Latitude = 01.3369, Longitude = 103.7364</p></li>
  </ol>
  
  <p><img src="https://i.stack.imgur.com/9s4Tc.png" alt="enter image description here"></p>
  
  <ol start="3">
  <li><p>Click the Register Geofence + BackgroundTasks button</p></li>
  <li><p>Exit the app (press the home button)</p></li>
  <li><p>Change the current location to anywhere 100m away from the location you set previously. A notification should pop out.</p></li>
  </ol>
  
  <h2>Project Code:</h2>
  
  <h3>Check for Location Capabilities</h3>
  
  <pre><code>    public static async Task GetLocationCapabilities()
      {
          try
          {
              var geolocator = new Geolocator();
              await geolocator.GetGeopositionAsync();
              var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
              Debug.WriteLine("background access status" + backgroundAccessStatus);
          }
          catch (UnauthorizedAccessException e)
          {
              Debug.WriteLine(e);
          }
          catch (TaskCanceledException e)
          {
              Debug.WriteLine(e);
          }
      }
  </code></pre>
  
  <h3>Create Geofence</h3>
  
  <pre><code>    public static void CreateGeofence(BasicGeoposition position, double radius, string id = "default")
      {
          // The Geofence is a circular area centered at (latitude, longitude) point, with the
          // radius in meter.
          var geocircle = new Geocircle(position, radius);
  
          // Sets the events that we want to handle: in this case, the entrace and the exit
          // from an area of intereset.
          var mask = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;
  
          // Specifies for how much time the user must have entered/exited the area before 
          // receiving the notification.
          var dwellTime = TimeSpan.FromSeconds(1);
  
          // Creates the Geofence and adds it to the GeofenceMonitor.
          var geofence = new Geofence(id, geocircle, mask, false, dwellTime);
  
          try
          {
              GeofenceMonitor.Current.Geofences.Add(geofence);
          }
          catch (Exception e)
          {
              Debug.WriteLine(e);
              // geofence already added to system
          }
  
      }
  </code></pre>
  
  <h3>Register Background Task</h3>
  
  <pre><code>    public static async Task RegisterBackgroundTask()
      {
          try
          { 
          // Create a new background task builder
          var geofenceTaskBuilder = new BackgroundTaskBuilder()
          {
              Name = GeofenceBackgroundTaskName,
              TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask"
          };
  
          // Create a new location trigger
          var trigger = new LocationTrigger(LocationTriggerType.Geofence);
  
          // Associate the location trigger with the background task builder
          geofenceTaskBuilder.SetTrigger(trigger);
  
          var geofenceTask = geofenceTaskBuilder.Register();
  
          // Associate an event handler with the new background task
          geofenceTask.Completed += (sender, e) =&gt;
          {
              try
              {
                  e.CheckResult();
              }
              catch(Exception error)
              {
                  Debug.WriteLine(error);
              }
          };
          }
          catch(Exception e)
          {
              // Background task probably exists
  
              Debug.WriteLine(e);
          }
      }
  </code></pre>
  
  <h3>BackgroundTask Code to Trigger Toast</h3>
  
  <pre><code>namespace BackgroundTask
  {
      public sealed class GeofenceBackgroundTask : IBackgroundTask
      {
          public void Run(IBackgroundTaskInstance taskInstance)
          {
              var toastTemplate = ToastTemplateType.ToastText02;
              var toastXML = ToastNotificationManager.GetTemplateContent(toastTemplate);
              var textElements = toastXML.GetElementsByTagName("text");
              textElements[0].AppendChild(toastXML.CreateTextNode("You have left!"));
  
              var toast = new ToastNotification(toastXML);
  
              ToastNotificationManager.CreateToastNotifier().Show(toast);
          }
      }
  }
  </code></pre>