Android蓝牙socket.connect()失败

use*_*317 7 sockets connection android bluetooth

我正在尝试在Android设备和RFID阅读器蓝牙之间建立连接.为此,我使用蓝牙聊天代码(蓝牙聊天示例).但是,当我mmSocket.connect();在蓝牙聊天示例的第329行进行时,每次都会生成连接java.io.IOException.我也试过这个方法来获取套接字:

tmp = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
Method m = mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(mDevice, 1);
Run Code Online (Sandbox Code Playgroud)

但没什么.我尝试了3种不同的设备.第一个,运行android 4.4.2的Samung S2给我这个错误:

failed:read failed, socket might closed, read ret: -1
Run Code Online (Sandbox Code Playgroud)

用平板电脑运行android 4.0.3给我这个错误:

IOException: Connection refused
Run Code Online (Sandbox Code Playgroud)

好奇心是,如果我尝试将手机与平板电脑连接,我就会失败.但是,如果我在这个应用程序的2个设备中运行,并且我尝试连接第二个,而第二个是搜索某些设备进行连接,则连接成功.但只有当第二个设备运行此应用程序并搜索某些设备才能连接时.我也试图取消配对,但没有.最后我想说,如果我尝试通过设置连接2台设备或一台设备与我的rfid蓝牙读卡器连接成功.最后我想说,当我尝试将2个设备或设备与读卡器rfid连接时,如果设备未配对,请比较一个要求我配对2设备的对话框,但此后连接失败.

Gil*_*mov 6

您的代码假定安全的BT连接,并尝试两种不同的方式(这是好的).您需要尝试的第一个测试是使用以下方法的不安全的BT连接:

BluetoothSocket sock;

// open API
sock = device.createInsecureRfcommSocketToServiceRecord(serviceUuid);

// if failed: hidden API
createMethod = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
sock = (BluetoothSocket)createMethod.invoke(device, 1);
Run Code Online (Sandbox Code Playgroud)


如果这不能解决问题,你应该问题.转到检查传递给创建方法的uuid的正确性.你可能(?)使用默认的SPP uuid:

UUID DEFAULT_SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Run Code Online (Sandbox Code Playgroud)

这适用于许多设备,但不是全部.


尝试询问您的同伴以获取它支持的uuids列表:

// for apiVer >= 15
supportedUuids = device.getUuids();


// for apiVer < 15
try {
   Class cl = Class.forName("android.bluetooth.BluetoothDevice");
   Class[] params = {};
   Method method = cl.getMethod("getUuids", params);
   Object[] args = {};
   supportedUuids = (ParcelUuid[])method.invoke(device, args);
}
catch (Exception e) {
    // no op
    Log.e("uuids", "Activation of getUuids() via reflection failed: " + e);
}
Run Code Online (Sandbox Code Playgroud)

并且,如果不为空,则使用数组中的第一个作为创建方法的参数.

您还可以使用由您自己编写的BTWiz,它在透明的直通模型中为您完成所有这些工作,并且还支持异步蓝牙IO.


Sam*_*ack 0

我有同样的问题。很容易解决。您必须使用他的配置程序将您的 RFID 阅读器配置为 SPP 协议,之后他才能工作。

  • 您能澄清一下解决方案吗? (12认同)