How can you “clear” the Bluetooth InputStream buffer from a device you've just connected to?

Also asked on stackoverflow.com

I am quite surprised that I cannot find anything related to this specific question. My goal is, when successfully connected to a Bluetooth device, to clear every byte from the buffer before beginning to listen for new data. The reason to why I want to do this is to make sure to get a clean series of data one at a time.

So far I’ve learned that reading from the InputStream “erases” the data from the buffer that is being read so I’ve added this piece of code after successfully connecting to the Bluetooth device as well. This should read and “erase” every data that is left in the buffer before reading for new data.

mmInputStream =newDataInputStream(btSocket.getInputStream());// Read/Erase leftover data #########while(mmInputStream.available()\>0){byte[] trash =newbyte[1024];int bin = mmInputStream.read(trash); trash[bin]='\0';}// ##################################  
beginListenForData();

I’ve quickly realized that mmInputStream.available() \> 0 is not always true even if there is more leftover data therefore it does not solve my problem. To reach the leftover data, I could run a task for n seconds that would read for any leftover data before beginning to listen for new data, but it would be dumb and boring since there could still be leftover data since I do not guarantee how many maximum possible would be leftover.

Too bad that there is no such thing as one simple method that would go like InputStream.clearBuffer() to the current Bluetooth device connected to mine.

1 Like