MobileWorking with Proximity APIs in Windows Phone 8

Working with Proximity APIs in Windows Phone 8

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

With the launch of Windows Phone 8, Microsoft introduced support for connections between devices that are within close range of each other.

Windows Phone 8 can now simply bump their phones to communicate between devices. This technology can be used in a variety of ways – share playlists, pay a friend, etc.

The Windows Phone 8 platform added APIs to programmatically support:

  • Using “Near Field Communications” technology to send data between devices running the same application.
  • Using a Windows Phone 8 device to interact with NFC tags.
  • Establishing connections between proximate devices over Bluetooth of Wi-Fi.
  • Exchange digital objects like digital business cards or v-Cards.

NFC (Near Field Communication) is a technology that allows communication between electronic devices over short-range wireless connectivity. NFC allows devices that are close together (within 1.5 inches of each other) to share data at a maximum of 424 Kbits/second.

To enable a Windows Phone 8 application to leverage proximity scenarios, the application needs to declare ID_CAP_NETWORKING and ID_CAP_PROXIMITY capabilities in the application manifest file, WMAppManifest.xml.

How Tapping Works with Proximity

Windows Phone 8 users can tap their devices to other Windows Phone 8 devices or Windows 8 devices to establish communication via NFC. Upon a successful tap, a socket is created over which communication happens with the other device. The connection can be TCP/IP or Bluetooth, depending on the settings of PeerFinder.AllowBluetooth and PeerFinder,AllowInfrastructure properties in the PeerFinder class. The most consistent connectivity experience is typically over Bluetooth.

Prerequisites

The Windows Phone 8 emulator does not support NFC. However, developer community members have created a tool over at codeplex.com that makes it possible to test and developer NFC/Proximity enabled Windows phone 8 apps without phone hardware. While this tool is not an exact replica of an actuall NFC device, it suffices for our learning purposes.

Download the ProximityTapper tool from http://proximitytapper.codeplex.com/ and install it.

Please note that when the tool is invoked the first time, it is necessary to give a complete Windows Firewall exemption to the tool, otherwise the tool might not work.

Hands-On

Create a new Visual Studio 2012 project titled WindowsPhoneProximityDemo.

New Visual Studio 2012 Project
New Visual Studio 2012 Project

When prompted, select “Windows Phone OS 8.0” as the target Windows Phone OS version.

New Windows Phone Application
New Windows Phone Application

Next, we declare the capabilities ID_CAP_PROXIMITY and ID_CAP_NETWORKING, which are needed for Bluetooth applications.

Open WMAppManifest.xml by double clicking in the Solution Explorer.

Open WMAppManifest.xml
Open WMAppManifest.xml

Next, add a few controls on the MainPage.xaml as shown under.

Add Controls
Add Controls

Add buttons titled “Discover Peers”, “Send Message” and “Receive Message” and a text box to report status.

Add Buttons
Add Buttons

On the code-behind for MainPage.xaml (MainPage.xaml.cs), include the following namespaces.

using Windows.Networking.Proximity;
using Windows.Networking.Sockets;

Next, add two properties to represent the ProximityDevice, StreamSocket and the published and subscribed message Ids.

namespace WindowsPhoneProximityDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        ProximityDevice device;
        StreamSocket _streamSocket;
        long publishedMessageId, subscribedMessageId;

On the click event of Discover Peers button, add code to start the PeerFinder and to register the event handler for the triggerConnectionStateChanged event.

private void buttonDiscoverPeers_Click(object sender, RoutedEventArgs e)
        {
            device = ProximityDevice.GetDefault();
            if (device != null)
            {
                PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged;
 
                PeerFinder.Start();
 
            }
 
        }

Now we need to implement the TriggerConnectionStateChanged method as shown below.

void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
        {
            switch (args.State)
            {
                case TriggeredConnectState.Listening:
                    textBoxStatus.Text = "Listening";
                    break;
                case TriggeredConnectState.PeerFound:
                    textBoxStatus.Text = "Peer Found";
                    break;
                case TriggeredConnectState.Connecting:
                    textBoxStatus.Text = "Connecting";
                    break;
                case TriggeredConnectState.Completed:
                    // Connection completed, retrieve the socket over which to communicate
                    textBoxStatus.Text = "Connected";
                    _streamSocket = args.Socket;
                    break;
                case TriggeredConnectState.Canceled:
                    textBoxStatus.Text = "Cancelled";
                    break;
                case TriggeredConnectState.Failed:
                    // Connection was unsuccessful
                    textBoxStatus.Text = "Failed";
                    break;
            }

In the method above, we will set the status textbox to represent any changes in connection status.

In the Click event for the “Send Message” button, we will add code to publish the message.

private void buttonSendMessage_Click(object sender, RoutedEventArgs e)
        {
            device = ProximityDevice.GetDefault();
            if (device != null)
                publishedMessageId = device.PublishMessage("Windows.SampleMessage", "WindowsPhoneProximityDemo");
 
        }

In the Click event for the “Receive Message” button, we will add code to subscribe to a message.

private void buttonReceiveMessage_Click(object sender, RoutedEventArgs e)
        {
            device = ProximityDevice.GetDefault();
            if (device != null)
                subscribedMessageId = device.SubscribeForMessage("Windows.SampleMessage", messageReceivedHandler);   
        }

Finally, we will implement the messageReceivedHandler method. In this method, we will update the textbox for status with the contents of the message.

private void messageReceivedHandler(ProximityDevice sender, ProximityMessage message)
        {
               textBoxStatus.Text = message.DataAsString;
        }
 
Now

Now, our application is code complete. If you are having issues compiling the application successfully, a sample code listing is available at <link> for downloading.

Now, we will execute out application. To actually test Proximity, we will need two physical devices or we will have to use the Proximity Tapper tool.

Summary

In this article, we learned about building Windows Phone 8 applications that leverage proximity APIs. I hope you have found this information useful.

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul.patel@hotmail.com  
 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories