我正在处理通过蓝牙接收的一些二进制数据,但是,当大量数据同时传入时,我的数据流中会丢失或无效字节。我希望有人可以帮助我解决这个问题,因为我需要一些帮助以获得更一致的回应。我同意简单地“扔掉”坏数据。以下是相关方法,它们在“Connected”线程内运行:
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int num_bytes = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
mmInStream.read(buffer, 0, 11);
processBytes(buffer);
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
private void processBytes(byte[] bytes) throws IOException {
if (bytes[0] != delimiter) {
int c;
do {
c = mmInStream.read();
} while (c != delimiter && c != -1);
if (c == -1) {
return;
}
}
/*Some processing happens here to generate the variables cellId and
voltage and cellId2 and voltage2
*/
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothInterface.DATA_READ,
new DataPoint(cellId, voltage)).sendToTarget();
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothInterface.DATA_READ,
new DataPoint(cellId2, voltage2)).sendToTarget();
}
最佳答案
我以前也遇到过这个问题。我不太确定是否通过在调用 processBytes 之前将流读入字符串对象来解决它。
关于java - Android 上通过蓝牙进行数据处理导致数据完整性不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5784567/