InputStreamから常にデータを読み取っているスレッドがあります。InputStreamデータはBluetoothソケットから来ています。以前は、InputStream読み取りステートメントの周りでif(mmInStream.available()> 0)を使用していませんでした。また、Bluetoothソケットがなくなったとき(誰かがデバイスの電源を切ったとき)、mmInStream.readはIOExceptionをスローし、その後、切断ロジックを処理します。切断がいつ発生したかを判断するための最良の方法は何ですか?
0xEEの最初のバイトはデータパケットのリーダーを示し、2番目のバイトは読み取る長さを示します。
public void run() {
byte[] tempBuffer = new byte[1024];
byte[] buffer = null;
int byteRead=0;
long timeout=0;
long wait=100;
while (true) {
try {
timeout = System.currentTimeMillis() + wait;
if(mmInStream.available() > 0) {
while((mmInStream.available() > 0) && (tempBuffer[0] != (byte) 0xEE) && (System.currentTimeMillis() < timeout)){
byteRead = mmInStream.read(tempBuffer, 0, 1);
}
if(tempBuffer[0] == (byte) 0xEE){
timeout = System.currentTimeMillis() + wait;
while(byteRead<2 && (System.currentTimeMillis() < timeout)){
byteRead += mmInStream.read(tempBuffer, 1, 1);
}
}
timeout = System.currentTimeMillis() + wait;
while((byteRead<tempBuffer[1]) && (System.currentTimeMillis() < timeout)){
byteRead += mmInStream.read(tempBuffer, byteRead, tempBuffer[1]-byteRead);
}
}
if(byteRead > 0){
//do something with the bytes read in
}
}
catch (IOException e) {
bluetoothConnectionLost();
break;
}
}
}