Steve Spencer's Blog

Blogging on Azure Stuff

Introducing NFC and Proximity with Windows Phone

Near Field Communication has been seen demonstrated in two ways. Firstly scanning an NFC enabled card which can be programmed to perform a number of different actions such as take your device to a specific url, transfer contact details, start an app or take you to the store to install the app and a number of other options. Secondly you may have seen people touching devices together to do things. These actions are either done via NFC communications in the same way that a tag works but also communication could be done using the proximity apis to create a personal network between the two devices to allow a richer sharing of data between devices. This post will cover NFC communication and will show you how you can use NFC to communicate data to devices both in a static way or programmatically as part of an app.

The simplest way to use NFC to exchange data Is via a physical NFC tag. These tags can be programmed with a range of information such as redirecting your mobile browser to a web page; sharing contact details or starting or installing an app. Each of these can be programmed using an app like the Nokia NFC Writer app documented here.

An NFC enabled device will automatically try and resolve the NFC tag data but it is also possible to have custom messages within a tag. Each tag has different capabilities and data sizes which can be seen here

The data that can be written to a tag can also be seen here

The common tag protocols are : WindowsUri, WindowsMime & NDEF.

NDEF is the Nfc Data Exchange format and is the Raw message format for NFC. This can be used to create custom messages for exchanging other types of data. Information about NDEF can be found here

What is more interesting though is that your phone is not only a reader of NFC data it can also be a sender of data so that the tap and send scenarios can be easily enabled within apps, providing that your device supports NFC.

The code samples below utilise the .NET Proximity APIs in C# and will show you how to add basic send and receive capability to an application.

Firstly you will need to determine whether the device your app is running on supports proximity. This is done by get hold of the default proximity device using:

ProximityDevice device = ProximityDevice.GetDefault();

If the device returned is null then you do not have NFC enable or your device down not have NFC capabilities. You can check to see if you have NFC on your phone in settings. There should be a section on NFC with a slider to turn NFC on or off. Make sure that it is turned on. You will also need to ensure that the capabilities of your app allows proximity and this is done in the app manifest file (ID_CAP_PROXIMITY)

Once you have your proximity device there are a number of events you can wire up which will get fired when another NFC device arrives whether that’s a static tag or an NFC enabled phone or tablet. These are DeviceArrived and DeviceDeparted and they fire as you would expect when the NFC device is tapped and when it is removed. These two event give you a notification about the arrival or departure but not the actual data. For this you will need to subscribe for messages and set up call backs to receive and process the NFC data. Similarly you can use the DeviceArrived event to allow you to send data to the other device.

To receive data you do not need to handle the DeviceArrived or DeviceDeparted events but you will need to subscribe for the set of messages you wish to receive including custom messages. You can create different handlers for each type of message you wish to receive.

long subscriptionID = device.SubscribeForMessage("Windows.BlackMarbleMessage", messageReceived);

Here I am subscribing to a custom message of type Windows.BlackMarbleMessage which my messageReceived method knows how to process:

private void messageReceived(ProximityDevice sender, ProximityMessage message)
{

    Debug.WriteLine("Received from {0}:'{1}'", sender.DeviceId, message.DataAsString);
    WriteMessageText(message.DataAsString);
}

My messageReceived method just takes the content of the message and displays it on the screen, but in a real life scenario the data could be JSON or XML for example and you process them accordingly.

The standard set of tag protocols is documented here if you want to access the raw NDEF protocol then the codeplex project here can be used

An application cannot determine whether the device arrived is an active device or just a passive tag so if you want to send messages out you need to understand that there may not be a response so make sure that your app is not expecting a response in order to proceed.

Sending data can be achieved by sending a message to the proximity device when you know that a device has arrived, so for this you will need to wire up the DeviceArrived event.

device.DeviceArrived += device_DeviceArrived;

.
.
.


void device_DeviceArrived(ProximityDevice sender)
{
    if (_bSendingMessage)
    {
        if(string.IsNullOrEmpty(_messageToSend))
                _messageToSend = "Hello World";
        sender.PublishMessage("Windows.BlackMarbleMessage", _messageToSend);
                
    }
            
}

This example is part of a phone app which needs to check a check box and enter some data in a text box in order to send data. Sending data is done through the PublishMessage, PublishBinaryMessage or PublishUriMessage methods. If you use PublishMessage or PublishBinaryMessage then you will need to add a string identifier for the message type which needs to match the message type that the receiver has subscribed to. In my example this is "Windows.BlackMarbleMessage".

Let's assume that we've installed this app onto two Windows 8 phones, one of the phones has the send message check box checked and has some data in the data check box. The two phones are Tapped together. Both apps will receive the DeviceArrived event and the device_DeviceArrived method is called on both apps. The phone with the send message check box checked will then send a Windows.BlackMarble message containing the data in the data text box to the other phone. The other phone then receives the message in its messageReceived method and will display it on the screen.

This is a basic example but it shows how you can send through simple message data and to add Tap functionality to you apps. This should work across devices and operating systems as the communication is through NFC (although you will need an app that understands your messages if you are sending custom messages).

NFC and proximity can be used to set up a longer running connection between two devices with or without tapping to initiate. There will be a follow on post that covers this shortly.