C# 使用Xamarin Android连接蓝牙扫描仪

C# 使用Xamarin Android连接蓝牙扫描仪,c#,android,bluetooth,xamarin,C#,Android,Bluetooth,Xamarin,我正在做一个项目,我需要连接到蓝牙扫描仪(摩托罗拉CS3070)。我需要捕获输入流,并使用它填充带有扫描条形码的列表框。我试图创建一个安全套接字并连接到它,但该套接字无法连接。(设备已打开并配对。如果光标位于可编辑字段中,它将作为物理键盘工作并填充扫描的代码)。这是我的代码: private static BluetoothAdapter bluetoothAdapter = null; private const int REQUEST_ENABLE_BT = 2; public sta

我正在做一个项目,我需要连接到蓝牙扫描仪(摩托罗拉CS3070)。我需要捕获输入流,并使用它填充带有扫描条形码的列表框。我试图创建一个安全套接字并连接到它,但该套接字无法连接。(设备已打开并配对。如果光标位于可编辑字段中,它将作为物理键盘工作并填充扫描的代码)。这是我的代码:

 private static BluetoothAdapter bluetoothAdapter = null;
 private const int REQUEST_ENABLE_BT = 2;
 public static ParcelUuid UUID;
 public static Dictionary<string, string> deviceDictionary = new Dictionary<string, string>();
 public static int STATE = 0;
 public static BluetoothSocket mySocket;
 public static Activity _activity;
 private static BluetoothReceiver receiver;
 private static BluetoothDevice pairedBTDevice;

 public void InitializeBluetooth()
    {
        // Get local Bluetooth adapter
        bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

        // If the adapter is null, then Bluetooth is not supported
        if (bluetoothAdapter == null)
        {
            Toast.MakeText(this, "Bluetooth is not available", ToastLength.Long).Show();
            Finish();
            return;
        }

        // If bluetooth is not enabled, ask to enable it
        if (!bluetoothAdapter.IsEnabled)
        {
            var enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
            StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        // Get connected devices
        var listOfDevices = bluetoothAdapter.BondedDevices;
        if (listOfDevices.Count > 0)
        {
            foreach (var bluetoothDevice in listOfDevices)
            {
                UUID = bluetoothDevice.GetUuids().ElementAt(0);
                if (!deviceDictionary.ContainsKey(bluetoothDevice.Name))
                    deviceDictionary.Add(bluetoothDevice.Name, bluetoothDevice.Address);
            }
        }
        else
        {
            connectButton.Text = "Scanner Not connected";
            connectButton.Clickable = false;
        }

        if (bluetoothAdapter.IsEnabled && listOfDevices.Count > 0)
        {
            if (listOfDevices.ElementAt(0).BondState == Bond.Bonded)
            {
                pairedBTDevice = listOfDevices.ElementAt(0);
                mySocket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.Uuid);
                var thread = new Thread(BTConnect);
                thread.Start();
            }
        }
    }

    public static void BTConnect()
    {
        try
        {
            mySocket.Connect();
            _activity.RunOnUiThread(() => connectButton.Text = " Scanner Connected");
            _activity.RunOnUiThread(() => connectButton.Clickable = false);
            receiver.loop = true;
            var thread = new Thread(BTRead, "BTRead");
            thread.Start();
        }
        catch (Exception e)
        {
            _activity.RunOnUiThread(() => Toast.MakeText(_activity.ApplicationContext, "Couldn't connect. Is the device on and paired?", ToastLength.Long).Show());
            _activity.RunOnUiThread(() => connectButton.Text = "Scanner Not connected");
            _activity.RunOnUiThread(() => connectButton.Clickable = true);
            receiver.loop = false;
        }
    }
私有静态BluetoothAdapter BluetoothAdapter=null;
私有const int REQUEST_ENABLE_BT=2;
公共静态PARCELUID UUID;
public static Dictionary deviceDictionary=new Dictionary();
公共静态int状态=0;
公共静态蓝牙插座mySocket;
公共静态活动;
专用静态蓝牙接收机;
专用静态蓝牙设备;
public void InitializeBluetooth()
{
//获取本地蓝牙适配器
bluetoothAdapter=bluetoothAdapter.DefaultAdapter;
//如果适配器为空,则不支持蓝牙
if(bluetoothAdapter==null)
{
Toast.MakeText(此“蓝牙不可用”,ToastLength.Long).Show();
完成();
返回;
}
//如果未启用蓝牙,请请求启用它
如果(!bluetoothAdapter.IsEnabled)
{
var enablebtent=新意图(BluetoothAdapter.ActionRequestEnable);
StartActivityForResult(启用BTIntent、请求\启用\ BT);
}
//获取连接的设备
var listOfDevices=bluetoothAdapter.BondedDevices;
如果(listOfDevices.Count>0)
{
foreach(设备列表中的var Bluetooth设备)
{
UUID=bluetoothDevice.GetUuids().ElementAt(0);
if(!deviceDictionary.ContainsKey(bluetoothDevice.Name))
deviceDictionary.Add(bluetoothDevice.Name、bluetoothDevice.Address);
}
}
其他的
{
connectButton.Text=“扫描仪未连接”;
connectButton.Clickable=false;
}
if(bluetoothAdapter.IsEnabled&&listOfDevices.Count>0)
{
if(listOfDevices.ElementAt(0.BondState==Bond.Bonded)
{
pairedBTDevice=listOfDevices.ElementAt(0);
mySocket=pairedbdevice.createrFComsockettoServiceRecord(UUID.UUID);
var线程=新线程(BTConnect);
thread.Start();
}
}
}
公共静态无效BTConnect()
{
尝试
{
mySocket.Connect();
_activity.RunOnUiThread(()=>connectButton.Text=“扫描仪已连接”);
_activity.RunOnUiThread(()=>connectButton.Clickable=false);
receiver.loop=true;
var线程=新线程(BTRead,“BTRead”);
thread.Start();
}
捕获(例外e)
{
_activity.RunOnUiThread(()=>Toast.MakeText(_activity.ApplicationContext,“无法连接。设备是否已打开并配对?”,ToastLength.Long)。Show());
_activity.RunOnUiThread(()=>connectButton.Text=“扫描仪未连接”);
_activity.RunOnUiThread(()=>connectButton.Clickable=true);
receiver.loop=false;
}
}
代码在
mySocket.Connect()行给出了一个异常
异常为
Java.IO.IOException:“读取失败,套接字可能关闭或超时,读取ret:-1”
。 我还尝试用我找到的一些示例创建一个后备套接字,但这对我没有帮助。有人能帮我解决这个问题吗

谢谢

编辑*我的应用程序具有以下蓝牙权限:

  • android.permission.BLUETOOTH_ADMIN
  • android.permission.BLUETOOTH
格雷厄姆对我的评价帮助了我,并将我推向了正确的方向。 我的代码的问题是,我假设第一个可用的Uuid将是连接到设备所需的Uuid

UUID = bluetoothDevice.GetUuids().ElementAt(0);
但我需要做的是首先检查UUID是否匹配蓝牙串行端口配置文件,从而过滤支持SPP的设备

BluetoothService.SerialPort是所有SPP设备的标准字符串
00001101-0000-1000-8000-00805f9b34fb


它还帮助我了解到,我的设备配置为使用HID蓝牙模式,而我需要在SPP模式下使用它。因此,我更新了代码,只过滤支持SPP的设备,然后使用
ConnectAsync()
连接到设备。现在我可以读取输入流了。

我们可以看到创建套接字的代码吗?
BluetoothSocket mySocket
被声明为类成员,创建套接字的代码在InitializeBluetooth()方法
mySocket=pairedBTDevice.createrFComSocketToServiceRecord(UUID.UUID)中。我做错什么了吗?