Near Field Communication (NFC) is an emerging, short range wireless technology. With a precise range of 2 cm, people can physically tap devices together to send/receive content. Tapping lets you select something (or someone) quickly. Not only is it quick, it’s also easy to understand. Once you see it, you get it; there’s no manual needed.

For example, imagine you are looking at some photos with a friend and she wants your pictures; with NFC, you can simply tap your device against her PC to send the photos. Over simplifying? Maybe, but the main idea is that it’s simple to share content between devices.

'This image shows the Nokia 360 speaker sharing its Bluetooth pairing information with a Windows Phone

Figure 1: This image shows the Nokia 360 speaker sharing its Bluetooth
pairing information with a Windows Phone

Similar to Bluetooth or Wi-Fi, NFC is a standard wireless protocol defined by the NFC Forum. Your PC needs an NFC radio. There are lots of Windows 8 PCs that have NFC radios integrated directly into them. If NFC isn’t already part of your PC, you can buy NFC dongles to plug into your PC.

NFC offers some cool capabilities. People can tap and send photos, tap a menu and order a meal at a restaurant, or even tap to pair a Bluetooth device.  These scenarios are pretty different from each other, but the thing they have in common is the 'tap' to initiate the experience.  NFC is used in variety of devices, such as PCs, phones, speakers, headsets, wireless displays, etc..., to make connecting devices together a really intuitive experience.  Also, NFC uses RFID tags; these are really cheap, lightweight passive antennas that can hold a sizable amount of data and can be stuck on virtually anything, most commonly posters.  For example, buying a movie ticket could be as simple as tapping the movie poster!  These are called NFC tags.  We'll walk through a basic example of tapping an NFC tag to demonstrate some key concepts of the NFC API.

But first, let’s take a closer look at what it means to tap devices together.

Defining a ‘Tap’

Whether you’re tapping to pair a Bluetooth mouse or tapping to share photos, it’s important for users to tap devices together the same way. And while tapping is a well understood concept, tapping your PC against another device is new to most people. Here are some guidelines for tapping that let users know:

  1. Where to tap devices together – by using a touchmark, also known as the ‘Tap and Do’ visual mark, indicating where the NFC antenna is located. Depending on the PC model, you tap different parts of the PC. For example, you may tap on the back on a tablet but on the front an all-in-one. Here’s what the mark looks like on any NFC enabled, Windows 8 PC:
    Tap and Do visual mark

    Figure 2: Tap and Do visual mark

  2. Devices are communicating with each other - During the tap, users should have confidence that something is going on; even if they can’t see the data being transferred. Therefore, Windows plays a sound when devices are in-range and communicating with each other.

Windows does these things automatically, so you won’t need to worry about them. For more info on these user experience elements, see the Windows 8 Near Field Proximity Implementation Specification. With that in mind, let's check out some of the cool scenarios you can experience with NFC.

When to use NFC

Use NFC when a user needs to select something, or someone, in your app. NFC gives you an intuitive way to select; and it’s often faster (and cooler!) than manually searching. The tap is a trigger to initiate an experience; and depending on your app, the experience can range from receiving a photo to starting a playlist. It’s really up to your app to decide what happens after the tap. So, to keep it simple, we classify this range of experiences as ‘Tap and Do’ experiences.

Below are a few examples of using NFC to select something in an app. You could Tap and…

  • Get information from a poster: NFC tags are light, cheap RFID tags; they cost between $0.15 - $1.00 (price varies on printing cost). These are comparable to QR codes, but are easier and faster to use.  Tapping a tag feels more comfortable than taking a picture of the bar code (and hoping the camera got the right angle).  Manufacturers are increasingly embedding tags into posters in high traffic areas like airports, metro stations, and bus stops. They can hold between 48 B – 4 KB of data. You can program a tag to launch your app to a specific page.
  • Exchange contact information: instead of spelling out your contact information to a friend, and hoping he didn’t misspell anything, tap devices together to exchange contact information. Similar to above, you can program your information to an NFC-business card/tag; or you could directly exchange information via an app.
  • Play your favorite music station: whether you’re about to go work out, hopping into your car or just lounging at home – use an NFC tag to start a radio station. You can even have different music stations programmed on different tags; for example, one tag for the gym, one for lounging, and one for sleep.
  • Order dinner at a busy restaurant: a popular restaurant at dinner time means you might be waiting a long time just to place an order. Instead, tap a tag at your table to order your food.
  • Play a multiplayer game with a friend: you can easily connect a multiplayer game like Battleship, Chess, or Scrabble with a friend by tapping devices together. After the tap, the connection persists over an out-of-band transport with a bigger range and higher throughput, such as Bluetooth or Wi-Fi Direct.

By now, we’ve got a pretty good idea of when to use NFC; now for fun stuff – building an app that uses our Windows 8 Proximity (NFC) APIs.

How to implement NFC

As you can see NFC makes lots of everyday tasks easier for end-users. Take setting an alarm for example. I’m sure just about everyone has had a few experiences where they mistakenly set their alarm for the wrong time in the morning. When its late and you just want to get to sleep, you’re not always thinking at your best. NFC makes this easier by letting you just tap a preset tag, confirm, and then go to sleep worry free. So to help users with this everyday task let’s imagine you wrote a basic alarm app that let users set an alarm using an NFC tag. This breaks into two scenarios

  1. Setting an alarm on the tag: NFC tags can be reusable, so the app should have a way for users to program an alarm. For example, a user may want to program different alarms – one for the week, another for the weekend. This is known as publishing data to a tag.
  2. Setting an alarm from the tag: After a user taps a tag, the app should launch to confirm setting an alarm. This means the app can be launched with context, or arguments.

The NFC API allows for several ways to achieve the same thing, but I’ll go over the simplest way to implement this scenario.

Let’s walk through a flow to set an alarm on an NFC tag:

  1. Mario launches the alarm app and sets a time, say 7.00 AM. Normal alarm stuff, nothing with NFC yet.
  2. Mario selects an option to ‘Set alarm on an NFC tag’. At this time, the app calls the NFC APIs to publish information to the NFC radio, specifically an app identifier string & 07:00. NFC tags use a standardized message format called NDEF, NFC Defined Exchange Format. Your app does not need to worry about formatting data into an NDEF message; Windows does this for you! Now, the user can tap the NFC tag.
  3. Mario taps the tag against the PC and the app confirms programming the tag. After the tag is tapped, it’s important to let users know that your app successfully programmed the tag. As we discussed earlier – tapping your PC is a new concept for most people, so the confirmation gives users confidence that what they just did worked. The app knows a message was successfully transmitted by registering for a message transmitted handler.

The NFC APIs are located in the Windows.Networking.Proximity namespace. They come into play at step 2 – after the user selects the option to ‘Set alarm on NFC tag.’ First, the app initializes a proximity object. The proximity object is used to tell when a tag (or device) is in/out of range. Next, we’ll add the DeviceArrival event handler. The handler recognizes when the tag has been tapped, which means we can start writing information to the tag. It’s useful to let users know when you’re writing to a tag, so they don’t move it out of range. You can use the same event to recognize when any proximity device has been tapped.

The next code snippet shows how to initialize and add a DeviceArrival event handler.

JavaScript

var proximityDevice;

function initializeProximityDevice() {
proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();

if (proximityDevice) {
proximityDevice.addEventListener("devicearrived", proximityDeviceArrived);

}
else {
// No NFC radio on the PC, display an error message
}


function proximityDeviceArrived(device) {
// Let the user know we’re ‘Writing to Tag’

}
}

C#
private void InitializeProximityDevice()
{

Windows.Networking.Proximity.ProximityDevice proximityDevice;
proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

if (proximityDevice != null) {
proximityDevice.DeviceArrived += ProximityDeviceArrived;

}
else
{
// No NFC radio on the PC, display an error message
}
}

private void ProximityDeviceArrived(Windows.Networking.Proximity.ProximityDevice device)
{
// Let the user know we’re ‘Writing to Tag’

}


Next, we publish information to the tag. The app publishes two things: an app identifier string, which consists of an app ID and app platform, and launch arguments. For Windows 8, the app Id is <package family name>!<app Id> and the app platform is ‘Windows.’ You must copy the app ID value from the ID attribute of the Application element in the package manifest for your app. The launch argument is ’07:00’ – the alarm set by the user. Let’s call this the message.

If the app works across platforms, Windows lets you publish alternate app ID(s) and app platform(s); which means you can tap the same tag on a different device which support NFC, like Windows Phone 8! You can find more information about Alternate IDs on MSDN.

The app publishes the data to the tag using a method called publishBinaryMessage. The method takes three parameters – messageType, message, and a messageTransmittedHandler function. We’ll set messageType to ‘LaunchApp:WriteTag’, which lets Windows know that your app wants to write information to an NFC tag. The message is just the message we defined earlier (app identified string and launch arguments); we’ll need to store the message as a binary message in a buffer. The messageTransmittedHandler function registers for callbacks. This lets your app know that the message has successfully been written to the tag. We’ll use this to tell the user two things: we’ve successfully written a message to the tag and the tag no longer needs to be in range.

Messages continue to be published until we call the StopPublishingMessage function or the ProximityDevice object is released. In this example, we’ll use the stop function. PublishBinaryMessage returns a publication ID; we’ll use this same publication ID to stop publishing the message onto the NFC Radio.

The next code snippet shows how to write data to an NFC tag:

JavaScript

var proximityDevice;

function getAlarmTime(){

// Grab time set by the user, call this variable ‘Alarm’
return Alarm;

}

function publishLaunchApp() {
proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

if (proximityDevice) {
// The format of the app launch string is: "<args>\tWindows\t<AppName>".
// The string is tab or null delimited.

// The <args> string can be an empty string ("").
var launchArgs = getAlarmTime();

// The format of the AppName is: PackageFamilyName!PRAID.
var praid = "AlarmApp"; // The Application Id value from your package.appxmanifest.

var appName = Windows.ApplicationModel.Package.current.id.familyName + "!" + praid;

var launchAppMessage = launchArgs + "\tWindows\t" + appName;

var dataWriter = new Windows.Storage.Streams.DataWriter();
dataWriter.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE;
dataWriter.writeString(launchAppMessage);
var launchAppPubId =
proximityDevice.publishBinaryMessage(
"LaunchApp:WriteTag",
dataWriter.detachBuffer(),
proximityWriteTagLaunchAppMessageTransmitCallback);

if (launchAppPubId != -1) {
// Stop publishing the message on NFC radio
proximityDevice.stopPublishingMessage(launchAppPubId);
}

}
}

function proximityWriteTagLaunchAppMessageTransmitCallback() {
// Inform the user that: the message has been successfully written to a tag & the tag no longer needs to be in range
}

C#
Windows.Networking.Proximity.ProximityDevice proximityDevice;

private string GetAlarmTime(){

// Grab time set by the user, call this variable ‘Alarm’
return Alarm;
}

private void PublishLaunchApp()
{
proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

if (proximityDevice != null)
{
// The format of the app launch string is: "<args>\tWindows\t<AppName>".
// The string is tab or null delimited.

// The <args> string can be an empty string ("").
string launchArgs = getAlarmTime();

// The format of the AppName is: PackageFamilyName!PRAID.
string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.

string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

string launchAppMessage = launchArgs + "\tWindows\t" + appName;

var dataWriter = new Windows.Storage.Streams.DataWriter();
dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
dataWriter.WriteString(launchAppMessage);
var launchAppPubId =
proximityDevice.PublishBinaryMessage(
"LaunchApp:WriteTag", dataWriter.DetachBuffer(),
proximityWriteTagLaunchAppMessageTransmitCallback);

if (launchAppPubId!= -1)
{
proximityDevice.StopPublishingMessage(launchAppPubId);
// Stop publishing the message on NFC radio
}

}
}

private void proximityWriteTagLaunchAppMessageTransmitCallback(
Windows.Networking.Proximity.ProximityDevice sender,
long messageId)
{
// Inform the user that: the message has been successfully written to a tag & the tag no longer needs to be in range
}

That’s it! Now you know how to write to an NFC tag from a Windows Store app. Simple enough; so, let’s move onto the next scenario - setting an alarm from the tag. Let’s walk through a flow to read an alarm from an NFC tag:
  1. Mario is reading his home screen/writing an email/playing a game/using Windows and he realizes he needs to set an alarm for Monday morning. He grabs his ‘Weekday alarm’ tag and taps it on his PC. He gets a toast inviting him to launch your Alarm app. Windows takes care of everything up until this point; your app doesn’t do a thing.
  2. Mario accepts and your app launches to a ‘Confirm Alarm?’ screen with a time of 7:00 AM. After Mario accepts the toast, Windows passes the launch arguments (same as above) to your app during activation. This is called contextual launching, which is the same thing as launching your app to specific page.
  3. Mario sets the alarm. Normal alarm stuff, no NFC.

It’s easy enough to get the launch arguments from the NFC tag. The app needs to handle contextual launching from an NFC tag. Contextual launching is the synonymous with launching your app to a specific page. Our launch arguments specify an alarm, 7.00 AM, which your app uses to display a proposed alarm. Also, in case your app isn’t installed on the PC, Windows invites Mario to install your app from the Windows store – automatically!

The following code snippet shows how to implement contextual launching.

JavaScript

app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket") {
//do nothing here.
}
else {
// Use args.detail.arguments to parse out ’07.00’ string, and display to the user
}

args.setPromise(WinJS.UI.processAll());
}
}

C#
async protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
{
_isLaunchedByTap = true;
}
else
{
// Use args.Arguments to parse out ’07.00’ string, and display to the user

}
Window.Current.Activate();
}


That’s all your app has to do to support reading and writing to an NFC tag; pretty simple for a cutting edge scenario. Before I wrap up, let’s go over some good hygiene stuff – error handling.

Error Handling

There are a few common errors your app may run into.

  • The tapped tag is not NDEF formatted. Windows 8 doesn’t support automatically reformatting a tag to NDEF, so you’ll need to download and install an NDEF formatter.
  • The tapped tag is read-only. Some NFC tags can be locked to read-only (similar to old school VHS tapes).
  • The tapped tag is too small and cannot hold all the data.
  • A users PC doesn’t have NFC. As I mentioned from the start, NFC is an emerging technology; widespread adoption is still growing. To check whether a PC supports proximity, use the ProximityDevice.getDefault() method; the method returns NULL if no NFC radios are installed.

It’s fun and intuitive!

NFC is finally here, ready for mainstream consumers – Windows has the ecosystem and a well-designed end-to-end UX. The technology has a lot of potential to make apps and device experiences incredibly interactive. It’s fun and intuitive.

NFC is a big area, so stay tuned for more blog posts on other cool Windows 8 NFC developer experiences.

For more info about NFC and proximity, check out the resources below.

Resources

Thanks,

Priya Dandawate
Program Manager, Devices and Networking

Contributions by: Max Morris, Marzena Makuta,  Mike Loholt, Jake Sabulsky, and Vishal Mhatre