Language: JavaScript and HTML | VB/C#/C++ and XAML

Proximity and tapping (Windows Runtime apps using C#/VB/C++ and XAML)

Applies to Windows and Windows Phone

Purpose

Note  

Proximity is designed for developers who want to incorporate easy connections into their app via a tap. This might include a multi-player game, for example, in which two users tap their devices together to establish a shared game session. Or, it could be an app in which customers tap a device and receive a link to a location where they can get more information or make a purchase.To make a connection between two devices using a tap gesture, both devices must have a proximity device, such as a Near Field Communication (NFC) radio.

You also can connect two PCs that are running your app, if they are in wireless range, by using peer browsing with Wi-Fi Direct. Similarly, you can connect two Windows Phones that are running your app, if they are within Bluetooth range, by using peer browsing. Once connected, the devices can share content such as photos or links, create a multi-player experience, or publish and subscribe to messages.

In this section

TopicDescription

Quickstart: Connecting apps using tapping or browsing

This topic walks you through the code you need to make your app capable of connecting to another instance of your app running on another device using proximity.

Quickstart: Publishing and subscribing to messages using tapping

This topic shows you how to use the PublishMessage and SubscribeForMessage proximity APIs to exchange messages between two devices using tapping.

Testing and troubleshooting proximity in apps

This topic provides guidelines for app developers to test and troubleshoot proximity in an app before submitting the app to the Store.

 

Roadmap: How does this topic relate to others? See:

Developer audience

You can use proximity to enable a quick exchange of data during a tap gesture, or you can use a tap to set up a long-term communication channel using Infrastructure network, Wi-Fi Direct, or Bluetooth.

Note  

Windows Phone: Setting up a communication channel using Wi-Fi Direct is not supported. You can only set up a long-term communication channel using an infrastructure network or Bluetooth.

Proximity is supported by the classes in the Windows Runtime that are in the Windows.Networking.Proximity namespace. You can use the ProximityDevice class to communicate with other devices within a range of 4 centimeters or less and exchange a small payload of data during the tap. You can use the PeerFinder class to communicate with peer apps and set up a long-term socket connection. A peer app is an additional instance of an app that's running on another device.

For example, the following code uses the GetDefault static method of the ProximityDevice class to get a reference to the proximity device for the local machine. By associating event handlers with the DeviceArrived and DeviceDeparted events, you can tell when a device enters or leaves proximity that is, comes within a range of 4 centimeters or less of your device.


Windows.Networking.Proximity.ProximityDevice proximityDevice;

public MainPage()
{
    InitializeComponent();

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

    if (proximityDevice != null)
    {
        proximityDevice.DeviceArrived += ProximityDeviceArrived;
        proximityDevice.DeviceDeparted += ProximityDeviceDeparted;
    }
    else
    {
        MessageTextBlock.Text += "Failed to initialize proximity device.\n";
    }
}



    Windows.UI.Core.CoreDispatcher _dispatcher = Window.Current.Dispatcher;

private async void ProximityDeviceArrived(object sender)
{
await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
            MessageTextBlock.Text += "Proximate device arrived.\n";
});
}

private async void ProximityDeviceDeparted(object sender)
{
await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
            MessageTextBlock.Text += "Proximate device departed.\n";
});
}       


For sample code that shows how to create a network connection between devices that are tapped together, see Quickstart: Connecting applications using tapping or browsing. For sample code that shows how to share small messages between devices that are tapped together, see Quickstart: Publishing and subscribing to messages using Tapping. For sample code that shows how to create multi-peer app connections and dynamically scan for peer apps within range using the PeerFinder, ProximityDevice and PeerWatcher objects, see the Proximity sample.

Important  

To use tapping in your app, you must enable the proximity capability in the package manifest of your app.

Important  

The Proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange sensitive user information such as passwords, financial data, text messages, email, photographs, or government ID numbers.

How to determine if proximity is supported

As mentioned earlier, a PC or phone must have a device installed that implements the Windows Proximity interface to use the proximity capability. (For information about implementing the Windows Proximity interface, see the Windows 8 Near Field Proximity Implementation Specification.) You can determine whether a device that supports proximity is installed by checking the PeerFinder.SupportedDiscoveryTypes property to see if Triggered connections are supported, or by checking whether the GetDefault method returns NULL, or by using the GetDeviceSelector method to get a list of the installed proximity devices and checking that it returns at least one.

Proximity is only enabled when your app is running in the foreground

All ProximityDevice and PeerFinder operations are disabled if your app is moved to the background. You can only publish and subscribe for messages or open socket connections if your app is running in the foreground. If you open a socket connection and your app is then moved to the background, your socket connection will remain open.

Activating apps using Proximity

When you use the PeerFinder and tap to connect your app to a peer app on another device, the user of the other device will be prompted to activate the app if the app is not already running or is not in the foreground. If the app is already running in the foreground, the activation event will be raised without prompting the user first. You can also activate an app that is not running in the foreground by calling the PeerFinder.Start method overload that takes a string parameter. The string parameter for the Start method contains a message that is sent to the peer app. The app will activate with the message passed to the activation arguments.

When you activate a peer app using a tap gesture, the app activates with an activation Kind of Launch. If you activate the app by sending a message using the PeerFinder.Start method, the message text can be retrieved from the Arguments property of the launch arguments. If your app is activated in order to open a StreamSocket, then the Arguments property will return the string Windows.Networking.Proximity.PeerFinder:StreamSocket. In this case, set the TriggeredConnectionStateChanged property to an appropriate event handler and call the PeerFinder.Start method to complete the socket connection. The following example is taken from the example code in Quickstart: Connecting applications using tapping or browsing and relies on the code in the OnLaunched event to pass the launch arguments.


protected override void OnNavigatedTo(NavigationEventArgs e)
{
    DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
    Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;

    // If activated from launch or from the background, create a peer connection.
    var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
    if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
    {
        if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
        {
            AdvertiseForPeersButton_Click(null, null);
        }
    }
}


Encrypting data sent over network sockets

If you open a StreamSocket using proximity and you'll be sending sensitive information over the network, you can encrypt the data being sent over the socket. For information on setting up encryption, see the SessionKey property and the CreateSymmetricKey method.

Socket communication protocol

When you send information to a peer app using a StreamSocket object, it is up to you to define the protocol for how the information is shared. For example, you might use an XML format, delimited name/value pairs, and so on. When the PeerFinder class creates a socket connection between peer apps, it connects the apps regardless of the version of the app. As a result, you may have two different versions of your app communicating with each other. For example, if a receiving app expects two 4-byte values and a newer version of the app sends the data as two 8-byte values to accommodate larger data, then the receiving app that expects 4-byte values will encounter an error while processing the data. You should take care to ensure that newer versions of your app can still communicate with older versions of your app using your communication protocol. That is, ensure that older versions of your app can ignore new information sent from a newer version of your app without encountering a problem.

Tip  

When peer apps communicate, you often need to determine which app will send the first message and which app will listen. One way that you can determine if your app is the sender or listener is to compare StreamSocket.Information.LocalAddress.CanonicalName to StreamSocket.Information.RemoteHostName.CanonicalName. By testing whether the local host name is greater than the remote host name, you'll always receive an opposite result between two instances of your app.

Related topics

Quickstart: Connecting applications using tapping or browsing
Quickstart: Publishing and subscribing to messages using Tapping
Guidelines for proximity
Testing and troubleshooting proximity in apps
Windows.Networking.Proximity namespace
Roadmap for creating apps using C#, C++, or VB
Samples
Proximity sample

 

 

Show:
© 2014 Microsoft. All rights reserved.