Proximity and tapping (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

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

Topic Description

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 SubscribeForMessageProximity 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  

For Windows Phone Store apps, 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";
    }
}
Private proximityDevice As Windows.Networking.Proximity.ProximityDevice

Public Sub New()
    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()

    If proximityDevice IsNot Nothing Then
        AddHandler proximityDevice.DeviceArrived, AddressOf ProximityDeviceArrived
        AddHandler proximityDevice.DeviceDeparted, AddressOf ProximityDeviceDeparted
    Else
        MessageTextBlock.Text &= "Failed to initialize proximity device." & vbCrLf
    End If
End Sub
    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";
});
}       
Private Async Sub ProximityDeviceArrived()
    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                        Sub()
                            MessageTextBlock.Text &= "Proximate device arrived." & vbCrLf
                        End Sub)
End Sub

Private Async Sub ProximityDeviceDeparted()
    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                Sub()
                            MessageTextBlock.Text &= "Proximate device departed." & vbCrLf
                        End Sub)
End Sub

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. You should avoid exchanging sensitive data with these APIs.

 

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);
        }
    }
}
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
    DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
    AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested

    ' If activated from launch or from the background, create a peer connection.
    Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
    If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then

        If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
            AdvertiseForPeersButton_Click()
        End If
    End If
End Sub

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.

 

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

Samples

Proximity sample