Home > Mobile >  For help, the Android USB receive data has always been fragmentation
For help, the Android USB receive data has always been fragmentation

Time:01-21

This code is my receiving data code, put a thread outside loop execution, but at the time of receiving data out of the question, a data, always be divided into many segments, and divided into several segments are not fixed, the length of each segment is not fixed, but when I add a delay here 500 ms after receiving data will be fixed into two segments, received a data first, and then the rest of the data in the receiving when they came together,
I guess it is because the external hardware to send data is a a hair, increase the delay, the second piece of data can be received together, without being divided into more than receiving, is there any way for the first time to receive when they receive the complete data?

Public byte [] the receive () {
ByteBuffer. The clear ();
Byte [] retbyte=byteBuffer. Array ();
Int ret=mDeviceConnection. BulkTransfer (usbEpIn retbyte, mMaxTransferSize, readOutTime);
If (ret & gt; 0 {
ByteBuffer. Position (ret);
Byte [] retData=https://bbs.csdn.net/topics/new byte [byteBuffer. The position ()];
System. Arraycopy (byteBuffer. Array (), 0, retData, 0, retData. Length);
L.i (TAG, "receiving data:" + DataConvert. Byte2HexString (retData));
return retData;
}
return null;
}

CodePudding user response:

MMaxTransferSize is how get?

CodePudding user response:

Byte is fluid, can only be read by the agreement, no complete data segments can only wait for, return retData; Here is wrong, should be a resolution protocol and see if meet a frame, satisfied to return.

CodePudding user response:

Posting a my code, note byte protocol run-on sentences:
 
ArrayList ListBytes=new ArrayList<> (a);
Byte [] buffer=new byte [maxPackageSize];
UsbEndpoint inEndpoint=usbInterface. GetEndpoint (0);
MainHandler. ObtainMessage (mainHandler WHAT_READING, "ready to read, please charge"). The sendToTarget ();
DeviceReading=true;
while (! Thread. Interrupted ()) {
Int ret=usbDeviceConnection. BulkTransfer (inEndpoint, buffer, buffer length, 200);
If (ret & gt; 0 {
Byte [] reab=new byte (ret);
System. Arraycopy (reab buffer, 0, 0, ret);
//the d (tag, "reads:" + bytesToHexString (reab));
//byte stream there
For (byte ab: reab) {
If (ab==0 (byte) x28) {
If (listBytes. The size () & gt; 0 {
Byte [] lineBytes=listBytes. ToArray (new Byte [0]).
GetCarCodeBytes (ArrayUtils toPrimitive (lineBytes));
ListBytes. The clear ();
}
} else if (ab!=0 x00 (byte)) {
ListBytes. Add (ab);
}
}
}
}
ListBytes. The clear ();
MainHandler. ObtainMessage (mainHandler WHAT_SHOW_MESSAGE, "stop reading"). The sendToTarget ();
  • Related