gpt4 book ai didi

java - 如何使用 bluecove 在 Java 中断开 BT 设备?

转载 作者:行者123 更新时间:2023-12-02 09:44:58 26 4
gpt4 key购买 nike

我是使用 Java 进行蓝牙通信的新手。查看 bluecove 文档,我执行了以下操作以便能够与蓝牙设备通信:

  1. 发现它
  2. 通过 Connector.open` 获取 StreamConnection
  3. 使用InputStreamOutputStream进行通信

我在文档中唯一没有找到的是如何关闭通信。

我实现的代码,猜测断开连接策略,如下:

    public void Connect() throws IOException
{
final int service = 5;
String conString = "btspp://"+Dev.getBluetoothAddress()+":"+service;

Connection = (StreamConnection) Connector.open(conString);
inStream = Connection.openInputStream();
outStream = Connection.openOutputStream();
}

public void Disconnect() throws IOException
{
Connection.close();
}

Dev 是我从 Discovery 获得的 RemoteDevice

当在 Disconnect 之后调用 Connect 函数时,我总是会得到以下异常:

javax.bluetooth.BluetoothConnectionException: Failed to connect; [10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.

有人可以告诉我如何关闭连接吗?

最佳答案

我找到了解决方案。对 Connection.close() 的调用必须在关闭通过调用函数 Connection.openInputStream()Connection 获得的流之后进行。 openOutputStream()

现在的断开连接函数如下:

    public void Disconnect() throws IOException
{
inStream.close();
outStream.close();
Connection.close();
inStream = null;
outStream = null;
Connection = null;
}

关于java - 如何使用 bluecove 在 Java 中断开 BT 设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56737414/

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