我有一个使用OutputStream
的写作线程,我希望实现flush()
方法。
As mentioned in the API,
OutputStream的flush方法不执行任何操作 并且应该在需要时实施。
我有以下主题,我对如何覆盖flush()
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// does nothing
mmOutStream.flush();
} catch (IOException e) {
}
}
谢谢!
答案 0 :(得分:3)
您的问题是关于“实施”flush()
,但您的代码未实现输出流。我想你要么问一下“使用”flush()还是你错过了getOutputStream()
返回一个OutputStream实现的事实,它很可能有一个工作的flush()(在某些情况下它是一个空的实现,因为如果流没有缓冲,则不需要特殊处理。)
我不确定您使用的是什么BluetoothSocket,但如果它是android.bluetooth.BluetoothSocket
,那么这将返回BluetoothOutputStream
,它将写入和刷新直接转发到BT套接字。
通常,您需要在单个消息/数据包的末尾调用flush()。将大量数据泵入流时,不应该调用它。 (因为如果这样做,可能会降低吞吐量并减少流实现的选项以减少开销)。