gpt4 book ai didi

java - 关闭 BluetoothSocket 的正确方法

转载 作者:搜寻专家 更新时间:2023-11-01 09:35:47 24 4
gpt4 key购买 nike

我以这种方式创建了 gpsSocket:

final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothDevice gpsDevice = bluetoothAdapter.getRemoteDevice(bluetoothAddr);
gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(RFCOMM_UUID);
gpsSocket.connect();

为简单起见,我删除了错误处理。

之后,我设置了一些东西以开始使用套接字:

final InputStream in = gpsSocket.getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "US-ASCII"));

如果我在从reader读取时捕获到异常,我是否应该关闭reader,或 gpsSocket,还是两者兼而有之?

最佳答案

根据经验,您应该始终注意关闭对象,即 Closeable

两者都是BluetoothSocketBufferedReader实现 Closeable 接口(interface),这意味着一旦您完成了该对象,您应该通过调用 close() 处理它们,否则您将结束内存泄漏。

结构应该是这样的:

BufferedReader reader;

try {
reader = ... // initialization
} catch (some exception) {
...
} finally {
if (reader != null) {
reader.close();
}
}

Should I close reader, gpsSocket or both of them?

您当然应该关闭阅读器。如果您不再需要 gpsSocket,那么您也应该关闭它。但如 documentation of BluetoothSocket.close() 中所示:

If the stream is already closed then invoking this method has no effect.

关于java - 关闭 BluetoothSocket 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43327931/

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