Communication between two phones using NFC
Article Metadata
Code Example
Article
What is NFC ?
NFC is the acronym for Near Field Communication; it's a wireless communication technology via radio-frequency which allows the exchange of data between a reader and a target or an NFC terminal at a distance of a few centimeters. Applications include contact-less transactions, data exchange, and simplified setup of more complex communications such as Wi-Fi or Bluetooth. Communication is also possible between an NFC device and an unpowered NFC chip, called a tag (a business card, for example).
NFC standards cover communications protocols and data exchange formats, and are based on existing radio-frequency identification (RFID) standards. The standards include ISO/IEC 18092 and those defined by the NFC Forum, which was founded in 2004 by Nokia itself, Philips and Sony, and now has more than 160 members.
NFC was present in a single Windows Phone 7 device, the Nokia Lumia 610 Quiksilver, exclusive for the French market. However, developers didn't have access to this feature .
NFC and Windows Phone 8
NFC communications are provided by the ProximityDevice class (namespace Windows.Networking.Proximity). To use NFC, you need to add a specific capability: open your WMAppManifest.xml and add the capability ID_CAP_PROXIMITY. If you don't do this, an exception will be launched when you will try to access the ProximityDevice.
Test if NFC is available
NFC chip-sets aren't mandatory on Windows Phone, so before we use NFC, it's necessary to test if it is present.
if (ProximityDevice.GetDefault() != null)
MessageBox.Show("NFC present");
else
MessageBox.Show("Your phone has no NFC or NFC is disabled");
Restrict your application to NFC-enabled devices
If NFC is essential for your application, you can specify in your WMAppManifest.xml file that your application must be only visible to phones with an NFC chip. To enable this, check the ID_REQ_NFC option in the Requirements tab.
Protocols
When you want to publish or subscribe to messages, you need to specify the type of messages you want. Message type values are case-sensitive strings consisted of one part or two parts:
- <protocol>.<subtype>
- <protocol>
The following table shows the supported values for the protocol part of the message type:
| Protocol | Description |
|---|---|
| Windows | The message contains binary data. |
| WindowsUri | The message data contains an URI (UTF-16LE encoded string). No subtype. |
| WindowsMime | The message data is of a specific MIME type. For example, if the message data is a JPEG image, the message type is WindowsMime.image/jpeg. |
| Windows:WriteTag | Same as the Windows protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications. |
| WindowsUri:WriteTag | Same as the WindowsUri protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications. No subtype. |
| LaunchApp:WriteTag | Write a tag that can be used to launch a specific app with optional launch parameters. If you publish a LaunchApp:WriteTag message to a tag the result when that tag is tapped to a computer is the same as calling the PeerFinder.Start method and passing your launch parameters. |
| WriteableTag | When subscribing for this message protocol, if a writable tag is brought in to proximity, a proximity message is received that contains an int32 (little endian) indicating the maximum writable size of the tag. This protocol is only valid for subscriptions. |
| NDEF | The message contents are properly formatted NDEF records. The underlying type of the content for a publication using NDEF as the message type is contained in the NDEF records. A subscription for the NDEF type subscribes to all NDEF formatted messages. |
| NDEF:ext | The message data is application defined NDEF records (TNF field value of 0x04). This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. |
| NDEF:MIME | The message data is a properly formatted NDEF mime message (TNF field value of 0x02). For example,NDEF:MIME.image/jpeg. This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. |
| NDEF:URI | The message data is a properly formatted NDEF message of a type defined by a URI namespace (TNF field value of 0x03).This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. This means that the data format is identified by the specified URI. |
| NDEF:wkt | The message data is a properly formatted NDEF message of a type defined by the NFC forum (TNF field value of 0x01).An example of this type isNDEF:wkt.U for the well known type of URI. This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. |
| NDEF:WriteTag | The message data should be written to an NFC forum standard static tag. The message data must be in a proper NDEF format. This protocol is only valid for publications. |
| NDEF:Unknown | The message data is an untyped NDEF message (TNF field value of 0x05).This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. |
The subtype is a string of alphanumeric characters and any of the valid URI characters as defined by RFC 3986: - . _~ : / ? # [ ] @ ! $ & ‘ ( ) * + , ; = %. The subtype cannot exceed a length of 250 characters.
Example: Windows.NokiaSample
Subcribe to a message
To subscribe messages, simply call the SubcribeMessage method and pass the message type that you want to listen to. In our example, we will ask to listen to messages of type Windows and as type NokiaExample.
var proximitydevice = ProximityDevice.GetDefault();
if (proximitydevice == null)
MessageBox.Show("NFC not present");
var subscriptionId = proximitydevice.SubscribeForMessage("Windows.NokiaExample", (device, message) =>
{
Deployment.Current.Dispatcher.BeginInvoke(() =>{
MessageBox.Show(message.DataAsString);
});
});
Be careful, the callback is not called in the UI thread !
Stop subscribing
The phone will continue to listen to NFC tags as long as your application will be executed. To stop the broadcast, call StopSubscribingForMessage method with the subscription ID returned from the SubscribeForMessage method.
proximitydevice.StopSubscribingForMessage(_subscriptionId.Value);
As soon as Windows Phone reads a NFC tag of the given type, the callback passed as a parameter will be executed.
Publish messages
We have seen how to subscribe to a message type, we will now see how to post a message. As previously, we will use the ProximityDevice object, but this time, we will use the PublishMessage method that takes two parameters:
- type
- message
var proximitydevice = ProximityDevice.GetDefault();
if (proximitydevice == null)
MessageBox.Show("NFC not present");
var subscriptionId = proximitydevice.PublishMessage("Windows.NokiaExample", "Hello you!");
A third parameter can be added allowing you to have a callback indicating that the message has been transmitted:
var proximitydevice = ProximityDevice.GetDefault();
if (proximitydevice == null)
MessageBox.Show("NFC not present");
var publishId=proximitydevice.PublishMessage("Windows.NokiaExample", "Hello you!",(device, messageId)=>{
Deployment.Current.Dispatcher.BeginInvoke(() =>{
MessageBox.Show("Message transmitted !");
});
});
The method returns a long value, that will serve you later to call the StopPublishingMessage method. Take in mind that the phone will continue to publish the message as long as you haven't stopped the publication.
Publish Uri or Binary messages
You can also use the PublishBinaryMessage or PublishUriMessage methods to publish binary or Uri message:
proximitydevice.PublishUriMessage(new Uri("http://www.nokia.com", UriKind.Absolute));
// OR
proximitydevice.PublishBinaryMessage("Windows.NokiaExample",stream);
Note: PublishUriMessage doesn't need type.
Stop publishing messages
To stop the broadcast of a message, call the StopPublishingMessage method using a publication ID returned from the PublishMessage, PublishBinaryMessage, and PublishUriMessage methods.
var proximitydevice = ProximityDevice.GetDefault();
proximitydevice.StopPublishingMessage(_publishId);
Publishing multiple messages
When you call the PublishMessage method many times, be aware that your new message will not overwrite the previous but will complete it. It's essential to call StopPublishingMessage before calling PublishMessage if you want to replace the previous message.
Sample code
Here's a Windows Phone 8 C# project that allows to demonstrate how to communicate between two phones: File:NFC WP8 sample app.zip

