Question

I have a writing thread, using OutputStream, and I want to implement a flush() method.
As mentioned in the API,

The flush method of OutputStream does nothing
and should be implemented if needed.

I have the following thread, and I'm a little bit confused about how should I override 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) {

            }

        }

Thanks!

Was it helpful?

Solution

Your question is about "implementing" flush() but your code is not implementing an output stream. I guess you either want to ask about "using" flush() or you miss the fact that getOutputStream() returns an implementation of OutputStream which most likely does have a working flush() (in some cases it is an empty implementation because no special handling is needed if the stream is not buffering).

I am not sure what BluetoothSocket you are using, but if it is android.bluetooth.BluetoothSocket then this is returning a BluetoothOutputStream which is forwarding both the write and the flush directly to the BT socket.

Typically you need to call flush() at the end of a single message/packet. You should not call it when you pump lots of data into a stream. (Because if you do you might reduce your throughput and reduce the options for the stream implementation to reduce overhead).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top