Working with Bluetooth APIs in Windows Phone 8

Introduction

Microsoft introduced support for Bluetooth in Windows Phone 8. Bluetooth is a technology that involves devices communicating with each other in the proximity of 10 meters or less wirelessly.

The Bluetooth APIs in Windows Phone 8 support app-to-app communication as well as app-to-device communication.

Bluetooth Basics

The first scenario for Bluetooth is called discovery/inquiry, where a device can enumerate discoverable remote devices that are in range. A device can then interrogate for a list of services that a particular remote device supports and then establish connectivity to that service on the remote device. This technology is used in multiple gadgets like wireless Bluetooth headsets, Bluetooth keyboards, Bluetooth speakers, etc.

As described above, Windows Phone 8 Bluetooth APIs supports two scenarios.

(1) App-to-app scenario – In this scenario, Bluetooth APIs are used by a Windows Phone 8 application to discover other applications whose service is desired to be used by the Windows Phone 8 application. After a connection is made, communication happens through a stream socket. Applications will need to declare the proximity capability: ID_CAP_PROXIMITY.

(2) App-to-device scenario – In this scenario, Bluetooth APIs are used by a Windows Phone 8 application to discover devices whose service is desired to be used by the Windows Phone 8 application. After a connection is made, communication happens through a stream socket. Applications will need to declare the proximity capability, ID_CAP_PROXIMITY, as well as networking capability, ID_CAP_NETWORKING.

Bluetooth Support in Windows Phone 8

Bluetooth 3.1 is supported in Windows Phone 8.

There are various Bluetooth user profiles, which are supported in Windows Phone 8.

(1) Audio/Video Remote Control Profile (AVRCP 1.4)

(2) Advanced Audio Distribution Profile (A2DP 1.2)

(3) Hands Free Profile (HFP 1.5)

(4) Phone Book Access Profile (PBAP 1.1)

(5) Object Push Profile (OPP 1.1)

Note that there is no emulator support for Bluetooth. You will need a real physical device to work with Bluetooth.

Hands-On

 Create a new Visual Studio 2012 project called WPBluetoothDemo.

Create a new Visual Studio 2012 project
Create a new Visual Studio 2012 project

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

Select the Windows Phone Platform
Select the Windows Phone Platform

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

Select Capabilities
Select Capabilities

Include the following namespaces in the code behind for the MainPage.xaml.

//MainPage.xaml.cs
using Windows.Networking.Proximity;
using Windows.Foundation;
using Windows.Networking.Sockets;

Next, add two button controls: one to start discovery of peer devices and the second for connecting to the peer. Also, add a textbox to display the name of the first peer device that is discovered.

Add two button controls
Add two button controls

Write the following code for the Click event of the “Discover Peers” button.

private async void buttonDiscoverDevices_Click(object sender, RoutedEventArgs e)
        {
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            var peerList = await PeerFinder.FindAllPeersAsync();
            if (peerList.Count > 0)
            {
                textBoxPeer.Text = peerList[0].DisplayName;
            }
            else MessageBox.Show("No active peers");
        }

The above code specified that only paired Bluetooth devices are to be discovered. This means that a Bluetooth device will need to be paired up to your test phone device before it can be discovered.

Next, when the user clicks the “Connect” button, we want to make a StreamSocket connection to the selected peer device. In our case, we will assume that we will connect to the first available peer device.

Write the following code for the Click event of the “Connect” button.

private async void buttonConnect_Click(object sender, RoutedEventArgs e)
        {
            
            var peerList = await PeerFinder.FindAllPeersAsync();
            if (peerList.Count > 0)
                textBoxPeer.Text = peerList[0].DisplayName;
            StreamSocket socket = new StreamSocket();
            await socket.ConnectAsync(peerList[0].HostName, "0");
        }

Finally, we need to prepare our application to respond to a connection request. For that we will wire up the PeerFinder.ConnectionRequested event to an event handler. We will setup with wiring on the Page Load event.

The code for that is below:

private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
        {
            PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;
        }
 
        void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
        {
            Connect(args.PeerInformation);
        }
        async void Connect(PeerInformation peerToConnect)
        {
            StreamSocket socket = await PeerFinder.ConnectAsync(peerToConnect);
        }
 

Our application is now complete. Deploy our application to two devices and run them, Pair the devices to each other before you click the “Discover Peers” button on one of the devices. Once the peer is discovered, you can click Connect to connect to the other device over Bluetooth.

In case you have trouble compiling the code, a sample listing of this project is available here.

Summary

In this article, we learned about Bluetooth support in Windows Phone 8 and how to build a simple Windows Phone 8 Bluetooth application. 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 

With the release of Windows Phone 8, Microsoft introduced support for using Bluetooth APIs in Windows Phone 8 applications. This article walks Windows Phone developers through the fundamentals of working with Bluetooth APIs in applications targeting Windows Phone 8 platform.

View Article



Downloads

Comments

  • Bluetooth paired device in wp 8.1 c#

    Posted by Ramachandran on 10/07/2014 05:13am

    Hi I want to show paired bluetooth device list should be show in my app.how can i handle that.pl guide me to handle that one.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Hundreds of millions of users have adopted public cloud storage solutions to satisfy their Private Online File Sharing and Collaboration (OFS) needs. With new headlines on cloud privacy issues appearing almost daily, the need to explore private alternatives has never been stronger. Join ESG Senior Analyst Terri McClure and Connected Data in this on-demand webinar to take a look at the business drivers behind OFS adoption, how organizations can benefit from on-premise deployments, and emerging private OFS …

Most Popular Programming Stories

More for Developers

RSS Feeds