gpt4 book ai didi

android - RFCOMM_CreateConnection - 已打开状态 :2, RFC 状态 :4, MCB 状态:5

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:26 32 4
gpt4 key购买 nike

我正在编写一个使用 RFCOMM 通过蓝牙连接到设备的 Android 应用程序。我使用 BluetoothChat 示例作为建立连接的基础,大部分时间一切正常。

但是,有时由于出现套接字已打开的消息,我无法重新连接:

RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5

如果我连接到设备,关闭应用程序(调用 onDestroy()),重新打开它并尝试再次连接,这往往会发生,这会导致上述情况。

我在 ConnectThread 中使用此方法进行连接(ref.BluetoothChat 示例):

Method m = device.getClass().getMethod("createRfcommSocket",new Class[] {int.class });
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
mmSocket = tmp;

解决此问题的唯一方法是关闭/打开 Android 手机的蓝牙。

这让我相信套接字没有在 onDestroy() 中关闭,但我仍然呼吁关闭所有线程,如前面提到的示例所示。
任何想法将不胜感激。

最佳答案

我也偶然发现了这个,这是我找到的答案:

如果多次打开和关闭蓝牙套接字连接,可能会发生此错误。

解决方案

从 API 级别 14 开始,BluetoothSocket 中有一个名为 isConected() 的方法。 ,如果此套接字已连接,则返回 true,否则返回 false,这里是 API 的原始摘录:

Get the connection status of this socket, ie, whether there is an active connection with remote device.

对于 < 14 的 API 级别,您可以通过在关闭连接后让蓝牙处理线程进入休眠状态来解决此问题 - 1000 毫秒应该足够了,这是一个示例(btDevice 是 BluetoothDevice 类型并且已经在下面的代码 fragment ):

    try {
//Open the socket to an SPP device (UUID taken from Android API for createRfcommSocketToServiceRecord)
BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord("00001101-0000-1000-8000-00805F9B34FB");
//Connect to the socket
btSocket.connect();
//Close the socket
btSocket.close();
//Sleep time of 1000ms after closing the socket
SystemClock.sleep(POST_RESET_DELAY);

} catch (Throwable e) {
// Log error message
}

附言除了 SystemClock.sleep,您还可以使用 Thread.sleep - 但是 SystemCock 的 sleep 不能被打断,而 Thread.sleep 可以被打断,所以这取决于您的用例,哪个选项更适合您的目的。

来源:Louis A. Prado

关于android - RFCOMM_CreateConnection - 已打开状态 :2, RFC 状态 :4, MCB 状态:5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7888294/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com