共用方式為


Bluetooth for Windows Phone 8

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

 

This topic provides an overview of how apps use Bluetooth in Windows Phone.

This topic contains the following sections.

 

Overview

Bluetooth is a wireless communication technology through which devices within a 10-meter proximity can communicate with each other. During what is called discovery/inquiry, devices can enumerate other devices within range that are in a discoverable state. Devices can then query the list of services that a particular device supports and ultimately establish connections to those services on the device. Using this technology, devices can communicate without a physical connection. Wireless headsets, remote control toys, and multiplayer games are examples of devices and apps that use Bluetooth technology.

Windows Phone 8 introduces API that you can use to develop apps that communicate using Bluetooth. Using these API, an app can connect to another app or to a device. These core scenarios open up a wide range of possibilities that you can use to make your app more connected.

Bluetooth scenarios

Windows Phone 8 supports two Bluetooth scenarios: app to app, and app to device. In each scenario a StreamSocket connection is established between the apps or devices.

App to app

In app-to-app communication, an app uses Bluetooth to discover another app that is advertising a service that the app wants to access. If the app finds another app within range that offers the service, the app initiates a connection request. When both apps accept the connection, a stream socket is opened between them through which the apps communicate.

App to device

In app-to-device communication, an app uses Bluetooth to discover a device that is offering a service that the app wants to access. If it finds a device within range that offers the service, the app initiates a connection request. When the app and the device both accept the connection, a stream socket is opened between them through which the app and the device communicate.

Peer discovery

Discovery is the process of finding a Bluetooth device or app that advertises a service with which you want to interact. In an app-to-device scenario, you can only discover devices that are already paired with the phone on which the app is running. Pairing is the process of using the Bluetooth control panel on your phone to find Bluetooth devices and then connect to them. Pairing typically involves sharing a PIN, or both sides agreeing to connect. In the case of app-to-app Bluetooth connection, one app is looking for another instance of itself on another phone. These phones do not need to be paired for discovery to occur.

Bluetooth API

To support third-party Bluetooth developer scenarios in Windows Phone 8, we’ve extended the StreamSocket and PeerFinder Windows Runtime APIs. This approach helps maintain consistency with the Windows 8 networking development model.

Class

Description

PeerFinder

Gives you the ability to discover another instance of your app on a nearby device, and create a socket connection between these peer apps. A peer app is another instance of an app running on another device.

PeerInformation

Contains info that identifies a peer app or device.

StreamSocket

Supports network communication using a TCP stream socket.

ConnectionRequestedEventArgs

Contains properties that are passed to an app by the ConnectionRequested event.

Required capabilities

The following table lists the capabilities that are required to enable the supported Bluetooth scenarios in Windows Phone 8. If these are not specified in WMAppManifest.xml, your app might not work correctly or it might fail the process of submission to the Windows Phone Store. For more info, see App capabilities and hardware requirements for Windows Phone 8.

Scenario

Required capabilities

App to app

ID_CAP_PROXIMITY

App to device

ID_CAP_PROXIMITY, ID_CAP_NETWORKING

Bluetooth profiles supported in Windows Phone 8 

Windows Phone 8 supports Bluetooth 3.1. This is an improved version of Bluetooth that automates the pairing process between Windows Phone 8 and Bluetooth devices, such as phone headsets, car audio systems, speaker docks, and NFC pairing. The following Bluetooth user profiles are supported.

  • Advanced Audio Distribution Profile (A2DP 1.2)

  • Audio/Video Remote Control Profile (AVRCP 1.4

  • Hands Free Profile (HFP 1.5)

  • Phone Book Access Profile (PBAP 1.1)

  • Object Push Profile (OPP 1.1)

  • Out of Band (OOB) and Near Field Communications (NFC)

Code examples

The following code examples show you how to use the Bluetooth API to connect to peer apps and devices, listen for connection requests, and check for Bluetooth availability.

Connect to a peer app

        async void AppToApp()
        {
            
            // PeerFinder.Start() is used to advertise our presence so that peers can find us. 
            // It must always be called before FindAllPeersAsync.
            PeerFinder.Start();

            var peers = await PeerFinder.FindAllPeersAsync();

            if (peers.Count == 0)
            {
                Debug.WriteLine("Peer not found.");
            }
            else
            {
                // Select a peer. In this example, let's just pick the first peer.
                PeerInformation selectedPeer = peers[0];

                // Attempt a connection
                var streamSocket = await PeerFinder.ConnectAsync(selectedPeer);

                DoSomethingUseful(streamSocket);
            }
            

        }

Connect to a device

To connect to a device over Bluetooth, the device must first be paired with the phone on which your app is running. You can discover paired devices using PeerFinder.FindAllPeersAsync. You can set the PeerFinder.AlternateIdentities with one of the key-value pairs in the following table:

AlternateIdenties setting

Notes

PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

Enumerate all paired devices. The PeerInformation.ServiceName will be empty in this case. For many devices, the Bluetooth port over which to communicate is hard coded, so you can use that directly in the ConnectAsync call. If the device is advertising a service, then you can enumerate using the paired option but call ConnectAsync with the GUID of the service you want to use. 

PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "<SDP service guid>";

Find devices using the Service discovery protocol (SDP) that are advertising a service with the given GUID. If any devices are found, the PeerInformation.ServiceName will be equal to the GUID you specified.

// Note: You can only browse and connect to paired devices!
private async void AppToDevice()
{
   // Configure PeerFinder to search for all paired devices.
   PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
   var pairedDevices = await PeerFinder.FindAllPeersAsync();

   if (pairedDevices.Count == 0)
   {
      Debug.WriteLine("No paired devices were found.");
   }
   else
   {
      // Select a paired device. In this example, just pick the first one.
      PeerInformation selectedDevice = pairedDevices[0];
      // Attempt a connection
      StreamSocket socket = new StreamSocket();
      // Make sure ID_CAP_NETWORKING is enabled in your WMAppManifest.xml, or the next 
      // line will throw an Access Denied exception.
      // In this example, the second parameter of the call to ConnectAsync() is the RFCOMM port number, and can range 
      // in value from 1 to 30.
      await socket.ConnectAsync(selectedDevice.HostName,"1");
      DoSomethingUseful(socket);
   }
}

If you enumerate by "Bluetooth:Paired", the PeerInformation.ServiceName field will be empty.  It is only populated when you enumerate using "Bluetooth:SDP". In this case the value returned in PeerInformation.ServiceName is the GUID value you set.  For many devices, the Bluetooth port over which to communicate is hard coded, so you can use that directly in the ConnectAsync call, as shown in the preceding example. If the device is advertising a service, then you can enumerate using the paired option but call ConnectAsync with the GUID of the service you want to use. 

Listen for a connection request

        // Page Constructor
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;
        }
         void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
        {
            if (ShouldConnect())
            {
                // Go ahead and connect
                ConnectToPeer(args.PeerInformation);
            }
            
        }

        async void ConnectToPeer(PeerInformation peer)
        {
            StreamSocket socket = await PeerFinder.ConnectAsync(peer);
            DoSomethingUseful(socket);
           
        }

        private bool ShouldConnect()
        {
            // Determine whether to accept this connection request and return
            return true;
        }

Detect the state of the Bluetooth radio on your phone

When Bluetooth is off, a call to FindAllPeersAsync will throw an exception. You would typically detect that Bluetooth was off on your phone by catching this exception in your code as follows.

   private async void FindPaired()
        {
          
            // Search for all paired devices
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

            try
            {
                var peers = await PeerFinder.FindAllPeersAsync();

                // Handle the result of the FindAllPeersAsync call
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    MessageBox.Show("Bluetooth is turned off");
                }
            }
        }

Notes

Issue

Workaround

Bluetooth peer-to-peer (P2P) advertisement isn’t enabled if you start, stop, and then restart PeerFinder.

Send your app to the background and then bring it to the foreground.

Bluetooth cannot be tested using Windows Phone Emulator.

Test Bluetooth using a Windows Phone 8 device.

See Also

Reference

Windows.Networking.Sockets..::.StreamSocket

Other Resources

Bluetooth app to app sample

Bluetooth app to device sample

Windows Phone 8: Networking, Bluetooth, and NFC Proximity for Developers (Build 2012)