问题
My Android app receive serial communication over bluetooth from desktop application. I have no control over what that desktop application is doing.
Using Google BluetoothChat sample code (https://github.com/googlesamples/android-BluetoothChat). I manage to make it working and to some extent I can simply took the bytes coming to my android app and write a file.
However, the code function is something like
1 - Android listen
2 - PC send data, Android accept connection read data and write to file
3 - While reading, Android encounter exception (client close connection?) and close the connection
4 - Back to one and listen for next few bytes
My problem is that I need to know when this process ends to process the file and display some result in the UI.
The code is this one file
https://github.com/googlesamples/android-BluetoothChat/blob/master/Application/src/main/java/com/example/android/bluetoothchat/BluetoothChatService.java
Specifically
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (mState == STATE_CONNECTED) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// ==> This is where I wrote to file
// ==> Standard Android Java code to write
// ==> to output file stream
// Send the obtained bytes to the UI Activity
// ==> Commented out because this can not be done here
// ==> NEED TO BE DONE WHEN ALL DATA IS READ
// mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
// .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
Expected there should be a way in Android RFCOMM or Bluetooth Communication to signify that client already finish sending all the communication.
Previously I try to use IoException as place to signal the UI that reading data from PC is done. That is a disaster because for some reason, exception only happen at the beginning of communication. And I have no idea why my codes still keep writing to file beyond that.
I am going to repeat that I have no control whatsoever on the PC/Desktop application. So please don't suggest anything that involve changing how desktop app operate or send data.
Need to handle this on Android side.
回答1:
You can never be sure that the far end has finished sending the data it wanted to send unless you have rules and/or some kind of protocol and start to parse the received data on your side.
Add/create a simple protocol with a header and a length-field that allow you to receive, and moreover, know what to expect in your receive-loop.
As a rule of thumb; never assume that you’ll get an entire packet in one read. Instead, buffer your received data and allow for multiple reads, before you eventually can process it and extract complete “packets” that conform to your specification.
来源:https://stackoverflow.com/questions/55351397/how-do-i-dump-serial-communication-as-file-through-android-bluetooth-serial-rfco