我正在尝试编写一个代码,该代码仅在运行Android 4.4 KitKat的Nexus 7上连接到我的(现在)配对设备。无论我尝试过多少东西,我仍然会遇到这个错误。这是我试过的最后一个代码,它似乎正在做我见过人们报告成功的一切。
有人能指出我做错了吗?
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();
答案 0 :(得分:1)
使用ELM327 OBD蓝牙适配器,我有完全相同的错误(IOException读取失败的套接字可能关闭或超时)。
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,然后我就可以连接 - 只需一次!循环重复......
问题已解决,如上文所述 - 创建一个INSECURE套接字。
btSocket = btDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
答案 1 :(得分:0)
你可以获得适用于Android的UUID< 3由此:
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();