Trigger a Background Task using Geofence on Windows Phone 8.1

UPDATE May 2, 2014: I mentioned using the emulator’s functionality to test geofencing in the initial blog post with placing multiple pins. It seems (after asking around internally at Microsoft) the Route option is the more reliable option to use in this case, as it simulates real behavior more accurately. Placing pins and jumping around on the map may conflict with the location optimization, resulting in unreliable trigger behavior.


With Windows Phone 8.1, we now have a range of ways to trigger a background task of our app. Aside from the previously available periodic timer that could trigger a background task, we can now also use raw push notifications, system events, device use triggers and location. The location method is used to trigger a background task using geofence, which we’ll be walking through in this post.

Setting up our solution

Naturally we’ll start out with a new Universal App to create a Windows and Windows Phone 8.1 app that share the same code base. For the purposes of this post, we’ll focus on Windows Phone 8.1, but the same principles can be applied to the Windows app. After creating our solution, we need to add an additional project that holds our background task. This is where the Windows Runtime Components come in, as the common runtime between Windows and Windows Phone 8.1 is now WinRT. Once created, add a reference to the new Windows Runtime Component from our WindowsPhone project.

Implement the background task

Delete the annoying Class1.cs file and create a new class. This class will inherit from IBackgroundTask to indicate it’s going to be a background task. This also requires us to implement the Run method, which will be called when our background task runs.

The following is sort of up to you, but I like to have three static methods on my background task class to register, unregister and check if it’s registered. Your implementation might vary (especially considering the SystemCondition you can apply to the task) The code I’m using is as follows:

Last, but not least, we need some logic for when our task will run. In this example, we’ll trigger a toast notification from the background task when it’s run (YES! that’s an option now on Windows Phone 8.1). Note that the logic that determines which report we filter from the GeofenceMonitor’s reports will vary for each implementation:

NOTE: If you plan on executing asynchronous code in your background task with async/await, make sure to use the IBackgroundTaskInstance.GetDeferral method to inform the system your task might continue to run after the Run method returns.

Implement the app logic

There’s a few changes we need to make to the Package.appxmanifest to set up our app for the background task using geofence:

  • As we’re creating a toast notification in the task, change Application > Notifications > Toast capable to Yes
  • To be able to use geofencing, we need to enable the Location capability under Capabilities > Capabilities
  • Lastly, we need to add a Background Tasks Declaration under Declarations > Available Declarations, ticking the Location Property and setting our Entry point to the full namespace of our task (e.g. GeofenceUniversalApp.Tasks.LocationTask)

Now that we’ve set up our manifest, we can start adding the logic to create and remove Geofences. Note I’ve also included a method to retrieve all current created geofences, so I can show them in my app. The code I’m using (in a static class) in this example is:

And that’s it! Now all we need to do is create a geofence in our app and register our background task. You can use the Windows Phone emulator’s tools to simulate the location of the device. If you trigger a pin outside the geofence area and then inside, the background task should trigger the toast notification. One side-note I do want to make is that it sometimes takes more than the 5 seconds of dwell time I’ve specified in the app logic for the task to trigger and that trying to trigger it multiple times in quick succession does not always work.

As always, the full solution can be downloaded below and reach me through the comments or on Twitter for questions, suggestions and/or feedback!

Downloads

Background Task using Geofence sample (970 downloads)
Pin It

34 thoughts on “Trigger a Background Task using Geofence on Windows Phone 8.1

  1. Pingback: Trigger a Background Task using Geofence on Windows Phone 8.1 - Rajen's Technical Tidbits - Site Home - MSDN Blogs

  2. Pingback: Trigger a Background Task using Geofence on Windows Phone 8.1

  3. I’m getting this error whenever I try to debug your implementation in my application:

    The program ‘[3944] BACKGROUNDTASKHOST.EXE’ has exited with code 1 (0x1).
    The program ‘[3752] VoiceWake.exe’ has exited with code 1 (0x1).

    the strange part is that I don’t get this error when debugging the solution you’ve supplied. I’ve compared projects extensively and cannot figure out the problem…

  4. I was keen to read your article and try out your code as since seeing it working in the Build videos I’ve then tried the MSDN GeoFence sample as well as attempt to wire it all up myself to have very inconsistent success in foreground and zero success getting anything to trigger from the background.

    Alas your implementation didn’t seem to alter that, with no Toasts being triggered from the background as I navigated around the Map (in ‘Route’ mode) around Microsoft Studio E (the location of your sample geofence). I’d previously put it down to something that just wasn’t working in the preview – I assume you’re not using any newer builds of the SDK that the general public have that might work better?

    Still keen to see it working ‘on my machine’ if you have any suggestions.

    Thanks,

    • Hi Ian,

      As mentioned, it doesn’t seem 100% consistent and reliable, but I definitely am getting toasts in both the emulator and on my device. Did you try my sample solution as is or did you build one yourself with the code in the article? If the latter, perhaps you missed changing the manifest to indicate the app to be toast capable (Application > Notifications > Toast capable to Yes)? If you put a breakpoint on the Run() method of your background task, does it break?

      I’m using the Visual Studio 2013 Update 2 RC build that’s publically available.

  5. Rajen, thanks for the code!

    I get toast messages when I enter the geofence (200m radius), however, I don’t often get them until long after I’ve been in the geofenced area (many minutes, even though I have the dwell time set at a few seconds).

    Is that some of the consistency/reliability issues you mention? Do you know how the location is actually working (does it use GPS, wi-fi, cell, or a combination)?

    • Hi Chris, that’s indeed what I’m talking about. I’ve tried it in a real-world scenario with a few devices/users and it doesn’t seem very consistent in its results. The location is determined by the device (at a time convenient for it without affecting battery life too much), so that might be a part of the reason why it’s not as precise.

  6. I tried the code in this article, and I can say that it works perfectly.

    I’ve noticed that sometimes toast notifications arriving after 30 seconds, but can also arrive after 3-4 minutes.

    it is possible to increase the frequency. I tried to act on Geolocator.ReportInterval but I have not gotten results.

    thank you

    • Hi Federico,

      Glad it works for you. The device does some optimization for battery life purposes, so the notifications will be throttled at some point. That’s probably the behavior your seeing.

  7. Hi you ! When I run geofencing in background task. I can’t call “id” from database and toast according to title of my database. I don’t want to set (r.Geofence.Id == “MyGeofenceId”) and toast with a text “You left …” . No way to fix it ? thanks

    • Hi Rahul, you can definitely make such an app, but please keep in mind the app needs to remain in the foreground to log data with such a short interval (30 seconds). If you are running in the background, every 15 minutes is the minimum interval you can achieve.

  8. Hi Rajen,
    I cannot find the download option/location, that you mentioned in your articel. Is this now lost?
    It your sample also working with Windows Phone 8.1?
    Until now I didn’t find any working example. Maybe there is a problem with the german numer definitions, but I also tried to work araound that…
    I hope, you have some informations.
    Thanks

    • Hi RoDi, thanks for the heads up. The download monitor plugin that I used was broken, but it’s been fixed now. The download link is at the bottom of the article.

  9. Since you seem to be using Linq, IsTaskRegistered() can be further simplified as follows:

    public static bool IsTaskRegistered()
    {
    return BackgroundTaskRegistration.AllTasks.Any(kvp => kvp.Value.Name == TaskName);
    }

  10. Hi Rajen,
    “◾Lastly, we need to add a Background Tasks Declaration under Declarations > Available Declarations, ticking the Location Property and setting our Entry point to the full namespace of our task (e.g. GeofenceUniversalApp.Tasks.LocationTask) ” I cant find a Location Property, also I enabled Location in the capabilities, is there some Visual Studio Settings to change?
    thanks a lot for your post btw!

    • Hi,

      You will find it in the app manifest under “Declarations”, when you add a new Background Task declaration (top left of the declarations window), you will see a list of Supported task types on the right side. Location is one of the boxes you can tick there.

  11. I am using my location aware app a couple of months already and can confirm that geofences are not triggered consistently. I know there are throttled by 2 min period between each notification but sometimes they are stuck even if the phone is consistently tracking location. Sometimes some geofences are skipped and trigger only when I remove and recreate geofences. It seems that the triggering algorithm need to be prompted/kicked to wake up.
    I thought maybe the geofences are throttled if too dense geographically by the said geofences were sparse,
    Any ideas? Has anyone spotted a ‘promising’ bug report?

  12. should the background task also notify if the app is closed?
    i am using windows mobile 10 and it seems the background task only trigger if the app is open and i am not sure if its by design (if that’s true a background task would not make sense) or the reason is windows mobile is in preview…

    • Hi Andre, it should definitely trigger if the app is not running (you can verify this in the Windows Phone 8.1 emulator for instance). I haven’t tried it on Windows 10 Mobile yet, but if it’s not working for you, it could very well be due to the preview status it has.

Leave a Reply

Your email address will not be published. Required fields are marked *