In this article, I'm going to cover the basics of getting your Band connected using a Background Task in a Windows Phone application.
If you've not yet discovered the basics of working with the Band SDK, check out my previous articles in this "Developing for Microsoft Band with WinRT" series. You'll need some experience to understand what I'm covering and how you can extend it to fit your needs.
Setup the background task
To get yourselves started with background execution, you'll need to add a new project to your solution that will be solely for your background task class. You'll need to create a new Windows Runtime Component, not a Portable Class Library.
You will then need to create a sealed class within this project that inherits from the IBackgroundTask interface in the Windows.ApplicationModel.Background namespace. You'll then need to add the interfaces only method, Run, that as indicated by the method name, runs when the background tasks are executing. It will provide you with a parameter that you can access a deferral from. You'll need to do this if you're going to be using your background task to access the data from the sensors.
The basic layout for this Run method will look like the following:
- public async void Run(IBackgroundTaskInstance taskInstance)
- {
- this._deferral = taskInstance.GetDeferral();
- // ToDo: Possibly check the cost of performing the BG task on the device. If high, then don't perform the task?
- try
- {
- // ToDo: Connect to the band and get the data
- }
- catch (Exception)
- {
- // ToDo: Complete the deferral and disconnect from the band
- }
- }
Getting Microsoft Band Data
NOTE: If want to access the Heart Rate sensor of the Band, you'll need to get the user's consent before the background tasks is registered to the phone since this is a new requirement in the SDK. The best way to do this is when your first page loads up. Connect to the Microsoft Band using the following method:
- private static async Task CheckBandStatus()
- {
- var bandInfo = (await BandClientManager.Instance.GetBandsAsync()).FirstOrDefault();
- IBandClient bandClient = null;
- bool isRunning = false;
- if (bandInfo != null)
- {
- using (new DisposableAction(() => isRunning = true, () => isRunning = false))
- {
- try
- {
- bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);
- }
- catch (Exception ex)
- {
- // ToDo: Log error?
- }
- if (bandClient != null)
- {
- if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
- {
- await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
- }
- }
- }
- }
- if (bandClient != null)
- {
- bandClient.Dispose();
- bandClient = null;
- }
- }
The preceding code will bring a dialog up in your application that your user will need to accept. If they refuse to do so, you can keep this method calling the next time the user enters your application to remind them that they need to do so if they want to use the Band sensors to track information in your app.
Now let's get the Band data in your background class. We'll create a new asynchronous private method called GetBandData that will set up the Band connection and register to listen for events fired by the Band's sensors. I'm providing you with the setup code but if you'd like to understand what you're doing, please go back and read my previous posts.
- private async Task GetBandData()
- {
- var bandInfo = (await BandClientManager.Instance.GetBandsAsync()).FirstOrDefault();
- bool isRunning = false;
- if (bandInfo != null)
- {
- using (new DisposableAction(() => isRunning = true, () => isRunning = false))
- {
- try
- {
- this._bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);
- }
- catch (Exception)
- {
- throw;
- }
- if (this._bandClient != null)
- {
- if (this._bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
- {
- // ToDo: Complete the deferral because we don't have consent to carry on
- return;
- }
- // Check the user is wearing the Band.
- var bandContactState = await this._bandClient.SensorManager.Contact.GetCurrentStateAsync();
- if (bandContactState.State == BandContactState.NotWorn)
- {
- // ToDo: Complete the deferral because the user isn't wearing the band. No need to read sensors.
- return;
- }
- this._heartRateRead = false;
- this._distanceRead = false;
- this._skinTempRead = false;
- this._bandClient.SensorManager.HeartRate.ReadingChanged += this.OnHeartRateChanged;
- await this._bandClient.SensorManager.HeartRate.StartReadingsAsync();
- this._bandClient.SensorManager.Distance.ReadingChanged += this.OnDistanceChanged;
- await this._bandClient.SensorManager.Distance.StartReadingsAsync();
- this._bandClient.SensorManager.SkinTemperature.ReadingChanged += this.OnSkinTemperatureChanged;
- await this._bandClient.SensorManager.SkinTemperature.StartReadingsAsync();
- }
- }
- }
- else
- {
- // ToDo: Complete the deferral as we can't find the connected Band on the device.
- }
- }
We're creating 3 methods to attach to our sensors and these will look something as in the following:
- private void OnSkinTemperatureChanged(object sender, BandSensorReadingEventArgs<IBandSkinTemperatureReading> e)
- {
- var skinTemperature = e.SensorReading.Temperature;
- this._skinTempRead = true;
- this._bandClient.SensorManager.SkinTemperature.StopReadingsAsync();
- this._bandClient.SensorManager.SkinTemperature.ReadingChanged -= this.OnSkinTemperatureChanged;
- // Do something with the skin temperature?
- this.CompleteReadings();
- }
- private void OnDistanceChanged(object sender, BandSensorReadingEventArgs<IBandDistanceReading> e)
- {
- var motionType = e.SensorReading.CurrentMotion;
- var pace = e.SensorReading.Pace;
- var speed = e.SensorReading.Speed;
- this._distanceRead = true;
- this._bandClient.SensorManager.Distance.StopReadingsAsync();
- this._bandClient.SensorManager.Distance.ReadingChanged -= this.OnDistanceChanged;
- // Do something with the distance readings?
- this.CompleteReadings();
- }
- private void OnHeartRateChanged(object sender, BandSensorReadingEventArgs<IBandHeartRateReading> e)
- {
- var healthRate = e.SensorReading.HeartRate;
- this._heartRateRead = true;
- this._bandClient.SensorManager.HeartRate.StopReadingsAsync();
- this._bandClient.SensorManager.HeartRate.ReadingChanged -= this.OnHeartRateChanged;
- // Do something with the heart rate readings?
- this.CompleteReadings();
- }
- private async void CompleteReadings()
- {
- if (this._heartRateRead && this._distanceRead && this._skinTempRead)
- {
- // Do something with the data we've received.
- // ToDo: Complete the deferral as we are now done in the background task
- }
- }
Here's that method:
- private async void CompleteDeferral()
- {
- if (this._bandClient != null)
- {
- this._bandClient.Dispose();
- this._bandClient = null;
- }
- this._deferral.Complete();
- }
Registering the Microsoft Band background task
The first thing you'll want to do to get set up with the registration process is to reference your background project from your Windows Phone or Windows project.
Once you've done that, you'll need to make a change to your app's manifest file so that it supports the background task. Depending on how you're wanting to trigger this, you'll need to choose the correct trigger from the app manifest. In this tutorial, I'll show you a time based one that runs every 15 minutes.
This is how your app manifest should look:

Figure: Microsoft Band background task
Now, after your call in the first page of your app that asks for access to the Band's sensors, you'll want to register your background task and here is how you do that:
- private static async Task RegisterTimerTask()
- {
- BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
- var builder = new BackgroundTaskBuilder { Name = TimerTaskId, TaskEntryPoint = typeof(BandUpdaterTask).FullName };
- var trigger = new TimeTrigger(15, false);
- builder.SetTrigger(trigger);
- builder.Register();
- }
You can now sit back and let your background task do all the work for your application!
If you have any questions, please feel free to leave them below and I will do my best to answer them.

Noor MohamedPosted Jun 18, 2015, 3:04 AM
Nice article
Santhakumar MunuswamyPosted Jun 17, 2015, 3:18 PM
Thanks for good work..
Gopi ChandPosted Jun 17, 2015, 1:54 PM
Great content with excellent explanation :)
Vijay SPosted Jun 17, 2015, 8:52 AM
Good one
NitinPosted Jun 17, 2015, 8:41 AM
good one