Bundling Inputstream.read Messages
Solution 1:
The 'read()' is blocking call and returns when few bytes are received over bluetooth. The count of 'few' is not fixed, and that's the reason why incoming response appears to be broken into pieces. Therefore to retrieve complete response, all these pieces must be joined together.
Where the response stream is terminated with a specific character, then following code logic can accumulate the bytes arriving before the terminating character. And once terminating character is detected, the accumulated response is sent to main activity. (Note that in the code snippet below, the terminating character used is 0x0a).
publicvoidrun() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = newbyte[9000];
int bytes;
ByteArrayOutputStream btInStream = new ByteArrayOutputStream( );
// Keep listening to the InputStream while connectedwhile (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
btInStream.write(Arrays.copyOf(buffer, bytes) );
if (buffer[bytes - 1] == 0x0a){
mHandler.obtainMessage(MainActivity.MESSAGE_READ, btInStream.size(), 0,btInStream.toByteArray());
.sendToTarget();
btInStream.reset();
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothThreading.this.start();
break;
}
}
}
Also note that code is not tested but proposed as one approach to resolve the issue mentioned in the question. Mat be it will need corrections at few places. Please test and inform the results.
Post a Comment for "Bundling Inputstream.read Messages"