Windows Phone 8 Bluetooth-Fehler HRESULT: 0x8007271D

Ich habe versucht, meine Windows Phone 8-App so zu entwickeln, dass sie auf ein gekoppeltes Bluetooth-Gerät (einen Drucker) zugreift und einige Druckdaten sendet.

Ich entwickle auf Windows 8 64bit und benutze VS2012 Express. Da der Emulator Bluetooth nicht unterstützt, habe ich das Build zu Testzwecken auf ein Nokia Lumia 820 hochgeladen.

Ich habe die folgenden zwei Websites als Referenz verwendet:

http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207007(v=vs.105).aspx

http://www.geekchamp.com/articles/getting-started-with-bluetooth-in-windows-phone-8

Die App findet das Pair-Gerät und gibt den Druckernamen über den Befehl Debug aus.

Der Code funktioniert bis zu dem Punkt:

await socket.ConnectAsync(selectedDevice.HostName, "1");

Und dann bricht es mit der folgenden Ausnahme:

********** EXCEPTION OCCURED **********
Data: System.Collections.ListDictionaryInternal
InnerException: 
Message: An attempt was made to access a socket in a way forbidden by its access permissions. (Exception from HRESULT: 0x8007271D)
StackTrace:    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at mobility.PrinterSettings.<AppToDevice>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
********** EXCEPTION OCCURED **********

Wenn ein Entfernen "warten" vor Socket.ConnectAsync (selectedDevice.HostName, "1"); Dann wird der Code ohne Fehler fortgesetzt, aber es wird keine Bluetooth-Verbindung hergestellt.

Ich habe jede Zahl von 1 bis 30 ausprobiert, wie in den Tutorials angegeben, und ich habe auch sichergestellt, dass ID_CAP_NETWORKING in WMAppManifest.xml aktiviert ist.

Bitte hat jemand eine Idee?

Vollständiger Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Networking.Proximity;
using System.Diagnostics;
using Windows.Networking.Sockets;
using Microsoft.Phone.Tasks;
using System.Text;
using Windows.Storage.Streams;

namespace mobility
{
    public partial class PrinterSettings : PhoneApplicationPage
    {
        public PrinterSettings()
        {
            InitializeComponent();
            PrinterName.Text = App.loadString("PrinterName");
            if (PrinterName.Text == null || PrinterName.Text == "")
            {
                PrinterName.Text = "QL420";
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (PrinterName.Text != null && PrinterName.Text != "")
            {
                App.saveString(PrinterName.Text, "PrinterName");
                MessageBox.Show("Printer Name has been saved.");
            }
            else
            {
                MessageBox.Show("Error: The Printer Name appears to be missing.");
            }
        }

        private async void AppToDevice()
        {
            try
            {
                // Configure PeerFinder to search for all paired devices.
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
                var pairedDevices = await PeerFinder.FindAllPeersAsync();

                if (pairedDevices.Count == 0)
                {
                    MessageBox.Show("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
                    Debug.WriteLine(selectedDevice.DisplayName); // Make sure we are trying to connect to the correct device.
                    //Debug.WriteLine(selectedDevice.HostName.RawName);
                    //Debug.WriteLine(selectedDevice.HostName.IPInformation.NetworkAdapter.NetworkAdapterId.ToString());
                    //Debug.WriteLine(selectedDevice.ServiceName);
                    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");

                    string newLabel = App.loadString("Template");
                    newLabel = newLabel.Replace("$n", "\n");
                    string epl = App.loadString("PrintHeader");
                    epl = epl + newLabel;
                    Debug.WriteLine(epl);
                    var data = GetBufferFromByteArray(Encoding.UTF8.GetBytes(epl));

                    //socket.OutputStream.WriteAsync(data);
                    MessageBox.Show("Device Found.");
                }
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    var result = MessageBox.Show("Bluetooth is turned off. To see the current Bluetooth settings tap 'ok'", "Bluetooth Off", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.OK)
                    {
                        ShowBluetoothcControlPanel();
                    }
                }
                else if ((uint)ex.HResult == 0x80070005)
                {
                    MessageBox.Show("To run this app, you must have ID_CAP_PROXIMITY enabled in WMAppManifest.xaml");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                    Debug.WriteLine(ex.HResult);
                }
            }
        }

        private IBuffer GetBufferFromByteArray(byte[] package)
        {
            using (DataWriter dw = new DataWriter())
            {
                dw.WriteBytes(package);
                return dw.DetachBuffer();
            }
        }


        private void ShowBluetoothcControlPanel()
        {
            ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
            connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
            connectionSettingsTask.Show();
        } 

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                AppToDevice();
            });
        }

    }
}

Antworten auf die Frage(1)

Ihre Antwort auf die Frage