我正在尝试与另一个电话建立蓝牙连接。稍后,它将是一个带有 HC5 模块的板,但为了调试,我只是使用手机。
问题是,连接失败并引发 IO 异常:“读取失败,套接字可能关闭或超时,读取 ret:-1”
一个快速的谷歌搜索显示很多有这个问题。我可以看到它解决的唯一方法是使用 API 中不公开的方法
Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
问题只是,它createRfcommSocket
已被删除,getMethod 的结果将为空。
我的代码来自示例:https://github.com/xamarin/monodroid-samples/tree/master/BluetoothChat用于连接的是:
public ConnectThread(BluetoothDevice device, BluetoothChatService service)
{
UUID MY_UUID = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
mmDevice = device;
_service = service;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try
{
if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4
tmp = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID);
else
tmp = device.CreateRfcommSocketToServiceRecord(MY_UUID);
}
catch (Java.IO.IOException e)
{
Log.Error(TAG, "create() failed", e);
}
mmSocket = tmp;
}
由于“原始黑客”不起作用,而且我还没有找到任何其他解决方案,我希望这里有人知道如何解决这个问题。
此致!