我已经成功将我的Android(6.0.1)手机(Sony Xperia Z3)与我的笔记本电脑(运行Ubuntu 14.04)配对。我可以来回发送文件。蓝牙连接菜单显示如果发送文件,连接开关将切换为ON。
我使用以下方法建立了持久连接:
sudo rfcomm connect rfcomm0 [MAC ADDRESS] [CHANNEL]
我想通过蓝牙将数据从手机发送到笔记本电脑。如果我运行此code,开关也会继续,但会立即关闭连接(开关返回OFF)。
调用init()
后,Logcat会显示以下警告:
W / BluetoothAdapter:getBluetoothService()调用no BluetoothManagerCallback
并且在调用write()
方法时出现此异常:
E /错误:错误init:java.io.IOException:读取失败,socket可能 关闭或超时,读取ret:-1
使用rfcomm
进行连接时,某些频道会失败并拒绝连接。我的猜测是我使用了错误的频道。
rfcomm
时了解使用哪个频道?答案 0 :(得分:1)
不知怎的,我无法使用方法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时知道要使用哪个频道?
发送sudo rfcomm listen rfcomm0
如何在Android应用中指定此频道?
我使用反射访问的方法现在具有此参数(createRfcommSocket
)
如何知道要使用哪个UUID?
在这个解决方案中没有。
在示例代码中使用了第一个UUID:为什么?
对于找到的解决方案无关紧要。