【发布时间】:2012-03-31 00:28:01
【问题描述】:
Android 有什么方法可以使用特定端口而不是使用服务 UUID 连接到蓝牙设备? 我知道此选项在其他提供蓝牙支持的平台上可用(例如,通过指定“btspp://”样式 URL 来指定 Java ME)。
谢谢!
【问题讨论】:
标签: android mobile bluetooth communication
Android 有什么方法可以使用特定端口而不是使用服务 UUID 连接到蓝牙设备? 我知道此选项在其他提供蓝牙支持的平台上可用(例如,通过指定“btspp://”样式 URL 来指定 Java ME)。
谢谢!
【问题讨论】:
标签: android mobile bluetooth communication
好的,已经有一段时间了,但我找到了解决问题的方法。我实际上打算放弃并使用 UUID,但我一直收到服务发现失败 (IO) 异常,当我试图找到服务发现问题的解决方案时,我找到了我原来问题的解决方案...... Ain' t生活吗?:)
无论如何,this is the link I stumbled upon,尽管您应该注意到答案中有一个错误(他们实际上只是连接到端口 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);
需要注意的几点:
祝大家好运。
【讨论】:
蓝牙 Android 连接仅通过 UUID 完成。每个蓝牙设备对其运行的每项服务都有一个 UUID(请参阅蓝牙 SDP)。
您只需为 Android 提供要监视的 UUID,在客户端模式下,它会自动找到要连接的套接字(包括端口)。在服务器模式下,它将等待指定设备使用指定的 UUID 发起连接。 BluetoothSocket 对象在建立连接时也有效(使用 getInput/Output Stream) 请参阅Server Socket documentation 和Client Socket documentation。
如果您真的想检查所有内容,您可以从其他设备的 SDP 和您提供的 UUID 中查看 Android 解码的内容。
使用this tutorial获取蓝牙接口(很容易做到)。 那么代码应该是这样的:
IBluetooth ib =getIBluetooth();
Int otherDevicePort = ib.getRemoteServiceChannel(otherDeviceAddress, UUID);
【讨论】:
我正在使用bluecove,它允许我使用函数Connector.open() 这样做。
我使用以下网址:
btspp://" + phoneID + ":" + phonePort
注意:可以添加一些选项(例如:authenticate=false; 或 encrypt=false;)。
phoneID 是蓝牙地址,phonePort 是端口号。
如何找到蓝牙地址? 来自这个link:
- 从主屏幕打开应用抽屉,然后打开“设置”。
- 选择“系统”。 (在某些型号上跳过此步骤)
- 向下滚动到底部,然后点按“关于手机”、“关于设备”或“关于平板电脑”。
- 向下滚动到底部并点按“状态”。
- 向下滚动,“蓝牙地址”将显示在列表中。
如何找到端口号? 我还没有找到应该使用哪个端口... 我使用了 5,它可以工作,但我需要研究原因,如果我想更换手机,我需要知道是否还需要更换端口。
【讨论】: