通过蓝牙将数据从 phone 发送到笔记本电脑

Send data from phone to laptop via Bluetooth

我已经成功地将 Android (6.0.1) phone (Sony Xperia Z3) 与笔记本电脑 (运行ning Ubuntu 14.04) 配对。我可以来回发送文件。蓝牙连接菜单显示,如果发送文件,连接开关切换到ON。

我使用以下方法建立了持久连接:

sudo rfcomm connect rfcomm0 [MAC ADDRESS] [CHANNEL]

我想通过蓝牙将数据从 phone 发送到我的笔记本电脑。如果我 运行 这个 code 开关也会打开,但会立即关闭连接(开关回到关闭状态)。

Logcat 在调用 init() 后显示以下警告:

W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback

并且在调用 write() 方法时出现此异常:

E/error: error init:java.io.IOException: read failed, socket might closed or timeout, read ret: -1

当使用 rfcomm 连接时,一些频道失败并拒绝连接。我猜是我用错频道了。

不知何故,我无法使用方法createRfcommSocketToServiceRecord

我当时所做的是删除:

ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());

并将这些行替换为:

int channel = 1; // substitute with channel you are listening on
Method m = device.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
BluetoothSocket socket = (BluetoothSocket) m.invoke(device, channel);

然后我发出 sudo rfcomm listen rfcomm0,然后显示它正在 Linux 终端上收听的频道,我终于可以连接了!

回答我自己的问题:

  • 调用rfcomm时如何知道使用哪个通道?
    Linux终端在发出sudo rfcomm listen rfcomm0

  • 时显示频道
  • 如何在我的 Android 应用程序中指定此频道?
    我使用反射访问的方法现在有这个参数 (createRfcommSocket)

  • 我怎么知道要使用哪个 UUID?
    在这个解决方案中 none.

  • 示例代码中使用了第一个 UUID:为什么?
    对于找到的解决方案无关紧要。