Proximity API
The Proximity API allows your UWP application to interact with devices that support proximity sensing, such as NFC (Near Field Communication) readers or other short-range wireless technologies. This API is primarily used for scenarios like peer-to-peer data transfer, device discovery, and initiating actions based on proximity.
Introduction to Proximity
Proximity sensing in UWP apps leverages hardware capabilities to detect when another proximity-enabled device is brought close to the user's device. This can enable a variety of innovative user experiences.
Key use cases include:
- Data Sharing: Quickly share contact information, files, or links between devices by tapping them together.
- Device Pairing: Simplify the Bluetooth or Wi-Fi Direct pairing process by bringing devices close.
- Triggering Actions: Launch an app or perform a specific action when a device enters proximity.
- Smart Card Interaction: Read data from or write data to smart cards or contactless payment terminals.
The primary classes involved in the Proximity API are within the Windows.Networking.Proximity namespace.
Core Concepts
Proximity Devices
A proximity device is a physical device that can detect the presence of another proximity device. Your application will interact with these devices through specific UWP classes.
Peer Finder
The Windows.Networking.Proximity.PeerFinder class is the central point for discovering and connecting to other proximity-enabled devices. It provides static methods to:
- Start or stop advertising your device's presence.
- Start or stop browsing for other nearby devices.
- Connect to discovered peers.
- Handle connection events.
ProximityDevice
The Windows.Networking.Proximity.ProximityDevice class represents a local proximity-enabled device. You obtain an instance of this class to publish and subscribe to proximity events.
Published and Subscribed Events
Your app can publish events that other devices can subscribe to, and it can also subscribe to events published by other devices. This allows for bidirectional communication and data exchange.
Key Classes and Methods
Windows.Networking.Proximity.PeerFinder
| Method | Description |
|---|---|
Start() |
Starts advertising your device to nearby peers. |
Stop() |
Stops advertising and browsing for peers. |
FindAllPeersAsync() |
Initiates a scan for all available nearby peers. Returns a task that resolves to a collection of PeerInformation objects. |
ConnectionRequested event |
Fired when another peer requests a connection. |
PeerArrived event |
Fired when a new peer is discovered. |
PeerDeparted event |
Fired when a peer is no longer detected. |
Windows.Networking.Proximity.ProximityDevice
| Method/Property | Description |
|---|---|
DeviceId |
Gets the unique identifier for the proximity device. |
PublishMessage(string messageType, string message) |
Publishes a message to subscribed peers. |
SubscribeForMessage(string messageType, MessageReceivedHandler handler) |
Subscribes to messages of a specific type published by other devices. Returns a handler ID. |
UnsubscribeFromMessage(long unsubscribeHelper) |
Unsubscribes from message publication. |
PublishSignalRange |
Gets or sets the signal range for proximity publishing. |
Id |
Gets the unique identifier for the proximity device. |
Windows.Networking.Proximity.PeerInformation
| Property | Description |
|---|---|
DisplayName |
Gets the display name of the peer. |
PeerId |
Gets the unique identifier for the peer. |
Code Example: Publishing and Subscribing to Messages
Here's a simplified C# example demonstrating how to publish a message and subscribe to messages from other devices using the Proximity API.
Publishing a Message
using Windows.Networking.Proximity;
using System;
// Assuming you have a ProximityDevice instance available
ProximityDevice myProximityDevice = ProximityDevice.GetDefault();
if (myProximityDevice != null)
{
try
{
string messageType = "MyCustomMessageType";
string messageContent = "Hello from my UWP app!";
myProximityDevice.PublishMessage(messageType, messageContent);
Console.WriteLine("Message published successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error publishing message: {ex.Message}");
}
}
else
{
Console.WriteLine("Proximity device not found.");
}
Subscribing to Messages
using Windows.Networking.Proximity;
using System;
ProximityDevice myProximityDevice = ProximityDevice.GetDefault();
long messageSubscriptionId = -1; // To store the subscription handler
if (myProximityDevice != null)
{
try
{
string messageTypeToSubscribe = "MyCustomMessageType";
messageSubscriptionId = myProximityDevice.SubscribeForMessage(messageTypeToSubscribe, (sender, args) =>
{
// This handler will be called when a message of the specified type is received
string receivedMessage = args.Message;
Console.WriteLine($"Received message: {receivedMessage}");
// You can process the receivedMessage here
});
Console.WriteLine($"Subscribed to messages of type: {messageTypeToSubscribe}");
}
catch (Exception ex)
{
Console.WriteLine($"Error subscribing to messages: {ex.Message}");
}
}
else
{
Console.WriteLine("Proximity device not found.");
}
// To unsubscribe later:
// if (messageSubscriptionId != -1 && myProximityDevice != null)
// {
// myProximityDevice.UnsubscribeFromMessage(messageSubscriptionId);
// Console.WriteLine("Unsubscribed from messages.");
// }
Permissions and Capabilities
To use the Proximity API, your application must declare the necessary capabilities in its Package.appxmanifest file.
Ensure you have the following capability declared:
<Capabilities>
<Capability Name="proximity" />
</Capabilities>
Without this capability, your application will not be able to access proximity devices or their functionalities.
Best Practices
- Handle Device Availability: Always check if a default proximity device is available using
ProximityDevice.GetDefault()before attempting to use any proximity features. - Manage Subscriptions: Ensure you properly unsubscribe from messages when they are no longer needed to prevent memory leaks and unnecessary resource consumption.
- Inform the User: Clearly communicate to the user when proximity features are active or when they need to bring devices close together.
- Error Handling: Implement robust error handling for all API calls, especially during message publishing and subscription.
- Privacy: Be mindful of user privacy when sharing data. Only share information that is necessary and has been explicitly consented to by the user.