在执行BluetoothSocket.connect()时出现java.io.IOException: read failed, socket might closed or timeout错误

5

我正在尝试编写一段代码,该代码仅连接到我的 Nexus 7(运行 Android 4.4 KitKat)上目前配对的唯一设备。无论我尝试了多少方法,我仍然遇到这个错误。这是我尝试过的最后一个代码,它似乎在做人们报告成功的所有事情。

有谁能指出我做错了什么吗?

BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter adapter = bluetoothManager.getAdapter();//BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
BluetoothDevice bt = adapter.getBondedDevices().iterator().next();
BluetoothDevice actual = adapter.getRemoteDevice(bt.getAddress());
String str = "";
for(BluetoothDevice bd : adapter.getBondedDevices()) {
    str += bd.getName() + "\n";
}
str+= actual;

textView.setText(str);
BluetoothSocket socket = actual.createInsecureRfcommSocketToServiceRecord(MY_UUID);
adapter.cancelDiscovery();
socket.connect();
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(message);
out.flush();

1
这就是异常所说的吗?我有点怀疑。请提供实际文本。 - user207421
3
那正是它所说的,包括糟糕的英语。 - Mr. Adobo
1
我设法让它工作了,但我不知道如何正确地做。通过使用BluetoothSocket socket = actual.createInsecureRfcommSocketToServiceRecord(actual.getUuids()[index].getUuid());获取我的套接字并手动硬编码索引的值,我成功找到了一个匹配的UUID。其余部分都引发了异常。不确定获取实际所需UUID的正确方法是什么。 - Mr. Adobo
2个回答

1
我遇到了完全相同的错误(IOException read failed socket might closed or timeout),这是由于ELM327 OBD蓝牙适配器引起的。
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
btDevice = btAdapter.getRemoteDevice(btDeviceAddress);
btAdapter.cancelDiscovery();
btSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();

ELM327可以实现第一次连接并正确地发送/接收,但只能一次。然后,所有后续的连接都会因IOException而失败。为了使其再次工作,我必须从操作系统中取消配对ELM327,然后才能连接 - 只有一次!这个循环不断重复...
问题已经像上面的帖子所描述的那样解决 - 创建一个不安全的套接字。
btSocket = btDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);

0

你可以通过以下方式获取 Android < 3 的 UUID:

Method method = device.getClass().getMethod("getUuids", null);
ParcelUuid[] phoneUuids = (ParcelUuid[]) method.invoke(device, null);
SERIAL_UUID = phoneUuids[1].getUuid();

或者:

UUID SERIAL_UUID = device.getUuids()[0].getUuid();

这是错误的:java.lang.RuntimeException: 在将结果ResultInfo{who=null, request=65538, result=-1, data=Intent { (has extras) }}传递给活动{de.myProject.activities.MainActivity}时发生了错误:java.lang.NullPointerException: 尝试从空数组中读取 - Mulgard
getUuids() 可能返回 null,你必须考虑到这一点。 - Shahar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接