有道关闭的BluetoothSocket
问题描述:
我已经gpsSocket
以这样的方式产生:有道关闭的BluetoothSocket
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothDevice gpsDevice = bluetoothAdapter.getRemoteDevice(bluetoothAddr);
gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(RFCOMM_UUID);
gpsSocket.connect();
我删除错误处理的简单性。如果我从reader
读书期间赶上例外
final InputStream in = gpsSocket.getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "US-ASCII"));
,我应该关闭reader
, 或gpsSocket
,或两者:
,我设置的东西后,开始与插座的工作?
答
作为一个经验法则,您应该始终注意关闭对象,即Closeable
s。
两个BluetoothSocket
和BufferedReader
实现Closeable
接口,这意味着只要您正在使用的对象之后,你应该通过调用close()
照顾从他们处置,否则你会最终内存泄漏。
结构应该是这个样子:
BufferedReader reader;
try {
reader = ... // initialization
} catch (some exception) {
...
} finally {
if (reader != null) {
reader.close();
}
}
我应该关闭读者,gpsSocket或两者?
您当然应该关闭reader
。如果您不再需要gpsSocket
,则还应该关闭它。但正如看到documentation of BluetoothSocket.close():
如果流已经关闭,则调用此方法无效。
但根据这个:http://*.com/questions/3956163/does-closing-the-inputstream-of-a-socket-also-close-the-socket-connection关闭流正在关闭因为'BluetoothSocket'与其他套接字有所不同,所以'socket.close()'将会是no-op,如果在'stream.close()'之前调用,或者引发异常,或者这不是相关的答案? – user1244932
请参阅[这里](https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close()):**如果流已关闭,则调用此方法不起作用。指定,你不需要明确地关闭它。 – azizbekian