Developing For Microsoft Band with WinRT - Indefinite Background Execution

In this post, I’m going to cover a more advanced version of the background execution code that I discussed in my previous Microsoft Band development post which looked at setting up a background task that ran on a timer to get data from the device. Here you’ll learn how to keep that connection open indefinitely using a DeviceUseTrigger background execution method.
Before I go into the explanation on how this works, you’ll definitely want to click the link above and check out my previous post. This post will assume that you’ve got a basic understanding of background execution and connecting with the Microsoft Band device in your app. If you want to catch up, here are some posts for you to get started: 

Most users developing applications that make use of the Microsoft Band’s sensors are looking to have them run in the background, especially when you’re creating a fitness app for the likes of running or home exercise. The problem with my previous post on background execution however is that it would only run for as long as it could before being cancelled meaning the user would have pieces of data from the Band with gaps. Luckily, I’ve taken a deeper look into background execution with Windows Phone and how you can use the Microsoft Band for a longer duration and that is what this post will cover.

When creating background tasks in Windows Phone, there are a number of ways that can trigger it to run. In my previous example, I used the TimeTrigger which allowed the background to run every 15 minutes. When developing that solution, I thought to myself “there must be a better way of keeping the Bluetooth connection open for as long as I possibly can”. Having a look at other Bluetooth background task samples on the MSDN website, I came across the DeviceUseTrigger which is intended to be used to access sensors and peripheral devices in background tasks even when the app is completely suspended.

Using DeviceUseTrigger with the Band 

Setting up the DeviceUseTrigger is relatively the same as how we set it up for the TimeTrigger except for a small change. When you use the DeviceUseTrigger, you have to request use of the device you’re trying to connect to by passing through the Device’s ID that is registered with your Windows Phone. This is done as follows: 
  1. public static async Task<bool> RegisterBandDataTask(string taskName)   
  2. {   
  3.     try   
  4.     {    
  5.         var access = await BackgroundExecutionManager.RequestAccessAsync();   
  7.         if ((access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) || (access == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity))   
  8.         {   
  9.             var taskBuilder = new BackgroundTaskBuilder { Name = "BandTask", TaskEntryPoint = taskName };   
  10.             var deviceUseTrigger = new DeviceUseTrigger();   
  11.             taskBuilder.SetTrigger(deviceUseTrigger);   
  12.             taskBuilder.Register();   
  14.             var device = (await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(new Guid("A502CA9A-2BA5-413C-A4E0-13804E47B38F"))))).FirstOrDefault(x => x.Name == bandInfo.Name);  
  16.             var triggerResult = await deviceUseTrigger.RequestAsync(device.Id);   
  17.             switch (triggerResult)   
  18.             {   
  19.                 case DeviceTriggerResult.DeniedByUser:   
  20.                     throw new InvalidOperationException("Cannot start the background task. Access denied by user.");   
  21.                 case DeviceTriggerResult.DeniedBySystem:   
  22.                     throw new InvalidOperationException("Cannot start the background task. Access denied by system.");   
  23.                 case DeviceTriggerResult.LowBattery:   
  24.                     throw new InvalidOperationException("Cannot start the background task. Low battery.");   
  25.             }   
  27.             return true;   
  28.         }   
  29.     }   
  30.     catch (Exception)   
  31.     {   
  32.         // ToDo   
  33.     }  
  35.     return false;   
  36. }   
Now I know this may look like a lot to go through but working with background tasks isn’t the easiest of tasks so I’ve given it to you all at once. I’ll break it down for you though so you fully understand what’s going on in the code snippet.

So, when you work with background tasks, you need to request access to the services. That is what is happening with the first few lines and if we’ve been granted the access to background execution, we can setup our background task with the DeviceUseTrigger and get it registered with the BackgroundExecutionManager. Unlike the TimeTrigger, we aren’t done yet with the set up however. At this point, we need to actually get the device ID and get the DeviceUseTrigger to request access to it. Even though we have our background task set up and ready to go, this final step needs to be made in order for the background task to be started. However, once this is complete, if your Microsoft Band is connected to your Windows Phone, it will immediately start running the background task and keep it running for an indefinite period of time. This is usually until your phone needs the memory to do OS based tasks or your Microsoft Band loses connection so you’ll need to handle this in your app and background task so that you unregister it successfully.

If you’d like to take a look at a sample of how this works, you can head over to my GitHub repo and have a play with it. If you have any questions or find issues, please feel free to drop me a line!

Enjoy developing with the Microsoft Band.

Similar Articles