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

dco*_*der 3 mobile android communication bluetooth

有没有办法让Android使用特定端口而不是使用服务UUID连接到蓝牙设备?我知道这个选项可以在其他提供蓝牙支持的平台上使用(例如,Java ME通过指定"btspp://"样式URL).

谢谢!

dco*_*der 9

好吧,已经有一段时间了,但我找到了问题的解决方案.我实际上打算放弃并使用UUID,但我一直收到服务发现失败(IO)异常,当我试图找到服务发现问题的解决方案时,我找到了原始问题的解决方案...... Ain'生活中的东西?:)

无论如何,这是我偶然发现的链接,但你应该注意到答案中有一个错误(它们实际上只是连接到端口1,而不是使用服务UUID).

在这个短暂的历史课后,这是解决方案:

使用反射,可以创建连接到端口号而不是UUID的Rfcomm套接字:

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);
Run Code Online (Sandbox Code Playgroud)

有几点需要注意:

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

祝你们好运.