1

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;
                }
            }

        }
4

3 に答える 3

1

available() では、このすべてのマラーキーは必要ありません。setSoTimeout で読み取りタイムアウトを設定し、読み取り、-1 を返す読み取りを検出し、バッファーがいっぱいになったと想定するのではなく、read によって返されたカウントを使用し、SocketTimeoutException をキャッチして読み取りタイムアウトを検出し、IOException をキャッチして他の破損を検出します。

于 2012-08-11T02:06:47.027 に答える
0

ドキュメントを見てみると、次のようになっていると思います。

public void run() {
    byte[] tempBuffer = new byte[1024];
    int byteRead = 0;

    while (true) {
        try {
            bytesRead = mmInStream.read(tempBuffer, 0, tempBuffer.length);
            if (bytesRead < 0)
                // End of stream.
                break;

            // Do something with the bytes read in. There are bytesRead bytes in tempBuffer.
        } catch (IOException e) {
            bluetoothConnectionLost();
            break;
        }
    }
}
于 2012-08-10T21:36:37.433 に答える