I am trying to read in data from an input stream, but if the program does not receive data for X amount of time, I would like to terminate the attempt and return a -1. I was previously using Thread.sleep( X ) but then realized that thats a completely incorrect approach. If anyone has any ideas please let me know. Here is my code for reading from the input stream…
try {
// Read from the InputStream
bytes = mmInStream.read(buffer, 0, length);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothService.this.start();
//break;
}
You can use Future to do this.
First, you need a class which will be returned as “future” value:
Then you need to use executor service and use get(long timeout, TimeUnit unit) like this:
In that way you will be able to achieve your goal. Plz note that its better to subclass Callable class which will accept inputstream as constructor argument then using class variables.