Microsoft Band SDK for Xamarin.Android

Xamarin and the Microsoft Band

Microsoft finally released an SDK for the Microsoft Band! Yay! The Band is very much designed for health and fitness uses with many sensors. But, it is certainly not limited to health uses. Because we have access to the sensors and can interact with the device, we can use the Band to enhance and extend our app. Working with Band essentially means communicating with the Band from the app installed on the device.

There are 4 main areas that we can interact with the Band:

  1. Reading information from the Sensors
  2. Creating themed app Tiles
  3. Sending Messages to the Band
  4. Theming and Personalizing the Band

The Library and Source Code

The Microsoft Band SDK is still in preview and is available on the official Developer page. When working with Xamarin.Android, we use the component from the Xamarin Component Store.

The binding 4, where you can fork, extend and improve. I will also be looking to create a PCL version that can be used in cross-platform apps, such as those using the Xamarin.Forms framework.

There are currently two demo apps to look at:

  1. Android Feature Demo – demonstrates all the features for Android
  2. Rotating Hand Demo – shows a simple example using the accelerometer (port from Iris Classon)

Getting Started

Before we can do anything with the Band, we need to be able to connect to it. This involves updating the Band and configuring the Xamarin.Android project.

First, we need to make sure that the latest Microsoft Health app is installed on the Android device and the Band updated with the latest firmware (done through the Health app). The Band needs to be paired with the Android device, and, the Health app needs to be synced with the Band.

Next, we need to ensure that we have set up our Xamarin.Android project with permissions to interact with the Band. The minimum supported Android version is 4.2, or level 17.

Finally, we need to make sure that we have permission to communicate with the Band over Bluetooth. This is easy to add using the [UsesPersmission] attributes:

    [assembly: UsesPermission(Android.Manifest.Permission.Bluetooth)]
    [assembly: UsesPermission(Microsoft.Band.BandClientManager.BindBandService)]

Connecting to a Band

Now that we have the Band, the device and the Xamarin.Android project set up, we can start connecting to the Band.

The first thing we want to do is get a list of the Bands paired with the device:

    var bands = BandClientManager.Instance.GetPairedBands();

Then we need to get an instance of IBandClient that will be used to communicate with the Bands:

    var client = BandClientManager.Instance.Create(this, bands[0]);

Once we have the client, we can connect to the actual Band:

    var result = await client.ConnectTaskAsync();
    if (result != ConnectionResult.Ok) {
        // we couldn't connect
    }

When we no longer require a connection to the Band, we can disconnect:

    await client.DisconnectTaskAsync();

Working with Sensors

Working with Microsoft Band Sensors

The main feature of the Band is the many sensors. The sensors that are available to us are the:

  • Accelerometer
    Provides X, Y, and Z acceleration in meters per second squared (m/sĀ²) units.
  • Contact
    Provides a way to let the developer know if someone is currently wearing the device.
  • Distance
    Provides the total distance in centimeters, current speed in centimeters per second (cm/s), current pace in milliseconds per meter (ms/m), and the current pedometer mode (such as walking or running).
  • Gyroscope
    Provides X, Y, and Z angular velocity in degrees per second (Ā°/sec) units.
  • Heart Rate
    Provides the number of beats per minute, also indicates if the heart rate sensor is fully locked onto the wearer’s heart rate.
  • Pedometer
    Provides the total number of steps the wearer has taken.
  • Skin Temperature
    Provides the current skin temperature of the wearer in degrees Celcius.
  • Ultraviolet (UV)
    Provides the current ultraviolet radiation exposure intensity.

Subscribing to sensors has an impact on the Band’s battery life. The use of each sensor requires power draw (some more than others), so we should only subscribe when the data is absolutely needed for our app.

Connecting to the sensors involves a few steps, namely getting hold of the sensor, attaching an event handler and then starting the sensor listener. So first, we want to get hold of a sensor:

    var accelerometer = client.SensorManager.CreateAccelerometerSensor();

Then we want to attach an event handler to the sensor so that we can be notified of updates. This is called from another thread and we need to be able to handle a high volume of events:

    accelerometer.ReadingChanged += (sender, args) => {
        var yReading = args.SensorReading.AccelerationY;
        RunOnUiThread(() => {
            label.Text = yReading;
        });
    };

Finally, we start listening to the sensor. Some sensors (namely the accelerometer and gyroscope) require a listening interval, or sample rate, which could be 16ms, 32ms or 128ms:

    await accelerometer.StartReadingsTaskAsync(SampleRate.Ms16);

When we want to stop listening, all we have to to is call one method:

    await accelerometer.StopReadingsTaskAsync();

Creating App Tiles

Creating App Tiles on the Microsoft Band

Tiles allow us to create app specific experiences on the Band. The Band supports up to 13 separate tiles, and will allow us to create as many tiles as there is space for.

If we want to find out how many tiles we can still create, we can use the TileManager:

    var capacity = await client.TileManager.GetRemainingTileCapacityTaskAsync();

Each tile consists of several properties:

  • a title or name
  • a tile icon
  • a small/badge icon
  • a theme/colour set

Creating App Tiles on the Microsoft Band

The band is required to have an ID (UUID), a title and an icon. If no small icon is provided, notification/badge numbers will not appear on the tile when a message is received. Each tile can have a custom theme, and if none is provided, then the current Band theme will be used.

The Band does not support colour icons, but only white, alpha blended icons. Also, each tile icon must be be 46×46 pixels. The small icon should be 24×24 pixels. Because the Band does not directly support the native Android bitmap, we use the BandIcon type:

    var options = new BitmapFactory.Options();
    options.InScaled = false;
    var icon = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Raw.tile, options)
    var tileIcon = new BandIcon(icon);

If we want to create a new tile, we use the BandTile.Builder:

    var uuid = Java.Util.UUID.RandomUUID();
    var tileName = "My Tile";
    var tile = new BandTile.Builder(uuid, tileName, tileIcon).Build();

We can also set a small icon and a custom theme:

    var tile = new BandTile.Builder(uuid, tileName, tileIcon)
        .SetTileSmallIcon(badgeIcon)
        .SetTheme(BandTheme.TuxedoTheme)
        .Build();

To add a tile to the band, we make use of the TileManager property:

    var success = await client.TileManager.AddTileTaskAsync(this, tile);

Removing a tile is also a single method on the tile manager:

    var success = await client.TileManager.RemoveTileTaskAsync(tile);

We can either pass the tile to the remove method, or we can just use the ID:

    var success = await client.TileManager.RemoveTileTaskAsync(uuid);

If we want to get a list of all the tiles on the device for our app, we can query the tile manager

    var tiles = await client.TileManager.GetTilesTaskAsync();

Sending Messages

We can display a notification for a tile using the NotificationManager property. There are three types of notifications:

  1. Dialogs
    A quick popup that the user can dismiss and the message will not be persisted on the Band. Dialogs have an accompanying single, short vibration.
  2. Messages
    A persistent notification that will remain in the tile. Up to 8 messages can be persisted before the oldest ones are removed to make room. If the tile has a small icon, the number of unread messages will appear on the tile. Messages may also have an accompanying dialog.
  3. Vibrations
    A haptic feedback mechanism that can be used to alert the user to a notification on the Band.

Each dialog consists of several properties:

  • a tile ID
  • a title
  • a body

A message is similar to a dialog, but contains an extra property:

  • a tile ID
  • a title
  • a body
  • a time stamp

To display a dialog, we need the tile ID, the title and a body:

    var title = "My Message";
    var body = "My explanation for the message.";
    await client.NotificationManager.ShowDialogTaskAsync(uuid, title, body);

Displaying messages is very similar, except there are a few extra parameters:

    var date = DateTime.Now;
    await client.NotificationManager.SendMessageTaskAsync(uuid, title, body, date);

If we want a dialog to appear along with the message, we can add an additional parameter:

    await client.NotificationManager.SendMessageTaskAsync(uuid, title, body, date, true);

To cause the Band to vibrate, we can specify a type of vibration:

    VibrationType vibration = ...
    await client.NotificationManager.VibrateTaskAsync(vibration);

Working with Themes

Working with Themes on the Microsoft Band

Using a theme on the devices could be the tile theme or changing the wallpaper. We can customize the Band in three ways:

  1. App Tile Theme
    This theme applies to only the app, and only when the app is open.
  2. Band Theme
    This theme applies to all the tiles and apps on the Band, except where the app has a custom theme. The tile on the Start Strip will use the Band theme, but once the app opens, it will use the app theme.
  3. Me Tile
    This is the background image on the Me tile. This tile is the first, large tile in the Start Strip.

Whether we customize our app tile theme, or the overall theme, we are provided a few, pre-defined themes. These include:

  • CornFlower
  • Cyber
  • Joule
  • Orchard
  • Penguin
  • Storm
  • Tuxedo
  • Violet

There are two parts to a theme, the tile colours and the app colours. The tile colours are:

  • Base
    This is the normal colour of the tile in the Start Strip. This colour is also used for the app’s back/app bar.
  • High Contrast
    This is the colour of the tile when there is a notification available.
  • Lowlight
    This is the colour of the visual feedback, when the user taps the tile or any buttons in the app.

The app colours are:

  • Highlight
    This is the colour of the app’s header text, such as the title in messages or dialogs.
  • Secondary Text
    This is the colour for other informational text in the app, whether the secondary header or date information in messages.
  • Muted
    This is the colour used when displaying notifications when the app is open, such as when a message is received.

When working with themes, we use the PersonalizationManager property. This provides a way to work with the theme or the Me tile background. In order to get the current theme that is set, we use the GetThemeTaskAsync method:

    var theme = await client.PersonalizationManager.GetThemeTaskAsync();

When we want to create a new theme, we can either modify an existing theme, or we can create a new BandTheme instance:

    var theme = new BandTheme {
        BaseColor = ...,
        HighContrastColor = ...,
        LowlightColor = ...,
        HighlightColor = ...,
        SecondaryTextColor = ...,
        MutedColor = ...
    }

Once we have our theme created, or just modified, we can apply it to the entire Band:

    await client.PersonalizationManager.SetThemeTaskAsync(theme);

If we want to use the theme with a single app tile, we must set it during the construction of the tile:

    var tile = new BandTile.Builder(uuid, tileName, tileIcon)
        .SetTileSmallIcon(badgeIcon)
        .SetTheme(theme)
        .Build();

Customizing the Me Tile

One of the first thing the user sees when looking at the Band is the Me tile. This is the first tile on the Start Strip and is where the date lies.

The background image on this tile must be exactly 210×102 pixels and should be in the RGB565 bitmap format. The bitmap instance type used by the API is Android.Graphics.Bitmap, the same type ised by the usual Android widgets.

If we want to access the image already on the Band, we can use the GetMeTileImageTaskAsync method:

    var bitmap = await client.PersonalizationManager.GetMeTileImageTaskAsync();

To set a new image, we use the SetMeTileImageTaskAsync method:

    await client.PersonalizationManager.SetMeTileImageTaskAsync(bitmap);