c# - 使用 Xamarin Android 连接到蓝牙扫描仪

标签 c# android bluetooth xamarin

我正在开发一个项目,需要连接到蓝牙扫描仪(摩托罗拉 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;
        }
    }

代码在 mySocket.Connect(); 行给出了异常,异常是 Java.IO.IOException: "read failed, socket might close or timeout, read ret: - 1”。 我还尝试使用我发现的一些示例创建一个后备套接字 on StackOverflow here但这对我没有帮助。有人可以帮我解决这个问题吗?

谢谢

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

  • android.permission.BLUETOOTH_ADMIN
  • android.permission.BLUETOOTH

最佳答案

格雷厄姆对我的 Xamarin Forum Thread 的评论帮助了我并插入我走向正确的方向。 我的代码的问题是我假设第一个可用的 Uuid 将是我需要连接到设备的 Uuid

UUID = bluetoothDevice.GetUuids().ElementAt(0);

但我需要做的是首先检查 Uuids 是否与蓝牙串行端口配置文件匹配,从而过滤支持 SPP 的设备。

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

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

关于c# - 使用 Xamarin Android 连接到蓝牙扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27685461/

相关文章:

c# - 如何引用 NuGet 包的匿名命名空间中的内容?

c# - 如何统一使用 JsonUtility 获取子数组

java - 使用 Java 解密代码截断 C# 加密数据

c# - 在我的数据库中更改 FK 的级联行为时需要更新模型吗?

java - 保存 List<Integer> 的状态

android - 在所有屏幕上 react native 抽屉导航器显示

java - Android 上的 DefaultHttpClient 或 HttpURLConnection

windows - 如何使用 Windows Phone 7 连接蓝牙打印机?

android - 在进行编程配对时,如何避免或关闭 Android 的蓝牙配对通知?

java - 无需连接设备的 Ble 扫描服务