更新时间:2023-10-05 09:23:40
好的,已经有一段时间了,但我找到了解决问题的方法.我实际上打算放弃并使用 UUID,但我一直收到服务发现失败 (IO) 异常,当我试图找到服务发现问题的解决方案时,我找到了我原来问题的解决方案...... Ain'有什么生活吗?:)
Ok, it's been a while, but I found a solution to the problem. I actually intended to give up and use UUID, but I kept getting a Service Discovery Failed (IO)exception, and when I tried to find a solution to the service discovery issue, I found the solution to my original question... Ain't life something?:)
无论如何,这是我偶然发现的链接,但您应该注意到答案中有一个错误(它们实际上只是连接到端口 1,而不是使用服务 UUID).
Anyways, this is the link I stumbled upon, though you should note there is a mistake in the answer (they actually simply connected to port 1, instead of using a service UUID).
在这个简短的历史课之后,这里是解决方案:
And after this short history lesson, here is the solution:
使用反射,可以创建连接到端口号而不是 UUID 的 Rfcomm 套接字:
Using reflection, it is possible to create the Rfcomm socket connecting to a port number instead of UUID:
int bt_port_to_connect = 5; // just an example, could be any port number you wish
BluetoothDevice device = ... ; // get the bluetooth device (e.g., using bt discovery)
BluetoothSocket deviceSocket = null;
...
// IMPORTANT: we create a reference to the 'createInsecureRfcommSocket' method
// and not(!) to the 'createInsecureRfcommSocketToServiceRecord' (which is what the
// android SDK documentation publishes
Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
deviceSocket = (BluetoothSocket) m.invoke(device,bt_port_to_connect);
需要注意的几点:
祝大家好运.