java - 尝试连接到配对设备时如何修复 "java.io.IOException: read failed, socket might closed or timeout"?

标签 java android bluetooth

我用当前与我的手机配对的设备创建了一个 ListView ,以便我可以选择其中一个并连接到它。为了确定选择了哪个设备,我将它们的 MAC 地址存储在一个数组中,以便我可以通过其地址获取设备。当我选择设备时,应用程序会卡住一段时间然后恢复,但无法成功连接。我在任何地方都找不到解决方案,我被困住了。我还是个初学者,不太明白。发生异常,如下所示:

java.io.IOException: read failed, socket might be closed or timeout, read ret: -1

这是我的代码。

// If the UUID is incorrect then this one does not work as well
// 00001101-0000-1000-8000-00805f9b34fb

private static final UUID CONNECTION_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");

public static boolean connectDevice(final int a) {

    try {
        BluetoothDevice mBluetoothDevice = btAdapter.getRemoteDevice(deviceAddress[a]);
        BluetoothSocket mBluetoothSocket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(CONNECTION_UUID);
        btAdapter.cancelDiscovery();

        mBluetoothSocket.connect();

        mmOutputStream = new DataOutputStream(mBluetoothSocket.getOutputStream());
        mmInputStream = new DataInputStream(mBluetoothSocket.getInputStream());

        mBluetoothSocket.close();

    } catch (NullPointerException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

最佳答案

根据您在代码中提供的CONNECTION_UUID,我假设您正在与蓝牙串行板连接。我还不确定这个问题,但是,我想写这个答案来提供一个可能解决您的问题的解决方案。

我认为在配对设备的情况下,您需要使用安全通道启动连接。目前,您正在使用不安全的 channel 。

来自documentation ...

The communication channel will not have an authenticated link key i.e it will be subject to man-in-the-middle attacks. For Bluetooth 2.1 devices, the link key will be encrypted, as encryption is mandatory. For legacy devices (pre Bluetooth 2.1 devices) the link key will be not be encrypted. Use createRfcommSocketToServiceRecord(UUID) if an encrypted and authenticated communication channel is desired.

因此,您可以考虑针对您的情况使用 createRfcommSocketToServiceRecord()

而不是这个

BluetoothSocket mBluetoothSocket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(CONNECTION_UUID);

使用这个...

BluetoothSocket mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(CONNECTION_UUID);

希望能解决您的问题。

来自下面的评论 - 此处实际工作的 UUID 是 00001101-0000-1000-8000-00805f9b34fb

关于java - 尝试连接到配对设备时如何修复 "java.io.IOException: read failed, socket might closed or timeout"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55797579/

相关文章:

java - 如果输入为 'y' 则重复循环

Android键盘滑动动画

ios - 订阅来自 CBCharacteristic 的通知不起作用

c - 结合使用 Arduino Motor Shield 和 Bluetooth Shield

java - 尝试清空 JTable 时出现 ArrayIndexOutOfBoundsException

java - 如何反转具有 O(1) 空间和 O(n) 时间的列表?

java - 来自其他包的 protected 方法调用

android - 使用点击上下文菜单选项打开上下文菜单

android - 在 Android-N 上以省流量模式使用数据

iOS 检查连接的外围设备 - Xamarin