class ReceiveThread extends Thread{
private boolean mReadSucc ;
private Handler mainThread = new Handler(Looper.getMainLooper());
@Override
public void run() {
super.run();
int readlen = 0;
byte[] buffer = new byte[1024];
ByteBuffer stickyBuffer = ByteBuffer.allocate(4096);
boolean foundHeader = false;
while (true){
if(!mIsServiceRunning){
break;
}
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
mReadSucc = false;
readlen = mInputStream.read(buffer);
mReadSucc = true;
} catch (IOException e) {
e.printStackTrace();
}
if(!mReadSucc || readlen == 0){
continue;
}
stickyBuffer.limit(4096);
stickyBuffer.put(buffer, 0, readlen);
stickyBuffer.flip();
while (true){
if(!stickyBuffer.hasRemaining()){
stickyBuffer.compact();
stickyBuffer.clear();
break;
}
stickyBuffer.mark();
if(stickyBuffer.remaining() < 4){
int remaining = stickyBuffer.remaining();
stickyBuffer.compact();
stickyBuffer.position(remaining);
stickyBuffer.limit(remaining);
foundHeader = false;
break;
} else {
short magicno = stickyBuffer.getShort();
if(magicno != (short) 0xC0DE){
continue;
} else {
foundHeader = true;
}
}
if (foundHeader){
int datatype = stickyBuffer.get() & 0xFF;
int datalen = stickyBuffer.get() & 0xFF;
if(stickyBuffer.remaining() < datalen) {
stickyBuffer.reset();
stickyBuffer.compact();
break;
} else {
byte[] databuf = new byte[datalen];
stickyBuffer.get(databuf);
processSerialData(datatype, databuf);
}
}
}
}
}