首页 > 解决方案 > 尝试连接配对设备时如何修复“java.io.IOException:读取失败,套接字可能关闭或超时”?

问题描述

我已经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;
}

标签: javaandroidbluetooth

解决方案


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

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

文档...

通信通道将没有经过身份验证的链接密钥,即它将受到中间人攻击。对于蓝牙 2.1 设备,链接密钥将被加密,因为加密是强制性的。对于旧设备(蓝牙 2.1 之前的设备),链接密钥不会被加密。如果需要加密和经过身份验证的通信通道,请使用 createRfcommSocketToServiceRecord(UUID)。

因此,您可以考虑将createRfcommSocketToServiceRecord()其用于您的案例。

而不是这个

BluetoothSocket mBluetoothSocket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(CONNECTION_UUID);

用这个...

BluetoothSocket mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(CONNECTION_UUID);

我希望这能解决你的问题。

从下面的评论中 - 在这里实际工作的 UUID 是00001101-0000-1000-8000-00805f9b34fb


推荐阅读