且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Android 连接到蓝牙设备上的特定蓝牙端口

更新时间: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);

需要注意的几点:

  1. 由于我们使用 Invoke,第一个参数是我们调用方法的对象,invoke 的第二个参数实际上是第一个函数参数)
  2. 还有一个可用的安全版本('createRfcommSocket'),它接受一个蓝牙通道号作为单个参数(同样,由于这是调用样式,您需要传递对象来调用方法,如-1- ) 中提到
  3. 我发现了这些函数原型的链接

祝大家好运.