Android bluetoothSocket连接错误

时间:2017-02-15 20:05:25

标签: android sockets bluetooth rfcomm

我正在尝试通过蓝牙从Android设备连接到HC-06。在使用之前我设法让它工作:

bluetoothSocket = (BluetoothSocket) bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(this.bluetoothDevice,1);

问题是它只能运行一次。当我断开并关闭输入和输出流然后关闭套接字,然后尝试重新连接它给我这个错误:

D/BluetoothSocket: connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[55]}
D/BluetoothSocket: close() in, this: android.bluetooth.BluetoothSocket@2d5fa8b, channel: 1, state: INIT
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@2d5fa8b, channel: 1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@39f43768, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@184d7781mSocket: android.net.LocalSocket@222b6026 impl:android.net.LocalSocketImpl@727b467 fd:FileDescriptor[55]
D/BluetoothSocket: Closing mSocket: android.net.LocalSocket@222b6026 impl:android.net.LocalSocketImpl@727b467 fd:FileDescriptor[55]
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
W/System.err:     at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:739)
W/System.err:     at android.bluetooth.BluetoothSocket.waitSocketSignal(BluetoothSocket.java:716)
W/System.err:     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:482)
W/System.err:     at com.example.work.dmm.clientBluetoothConnection.run(clientBluetoothConnection.java:65)

我试图搜索问题并发现各种帖子说应该使用createRfcommSocketToServiceRecord()。我试过了:

ParcelUuid[] uuids = bluetoothDevice.getUuids();
UUID uuid = uuids[0].getUuid();
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);

但这根本不起作用。我不知道从哪里去,所以任何帮助都表示赞赏。

1 个答案:

答案 0 :(得分:0)

当断开连接然后重新连接时也遇到同样的问题我得到一个错误,但在我的情况下有一个广播接收器,当蓝牙适配器重新打开时接收到一个动作。这是破坏适配器完全重新开启的原因,所以我删除了那部分代码并且它工作了......在断开连接后重新连接它工作正常。