0

我已经设置了一个套接字来接收来自蓝牙设备的数据。接收缓冲区设置为在退出线程之前收集 8 个字节的数据,但缓冲区不会提前存储下一个字节的数据。我将缓冲区设置为 8 并循环直到缓冲区已满。

      private class ConnectedThread extends Thread {

    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = btSocket.getInputStream();
            tmpOut = btSocket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
        }

    public void run() {

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {

                InputStream mmInStream = btSocket.getInputStream();

                byte[] readBuffer = new byte[8];
                int read = mmInStream.read(readBuffer);
                while(read != -1){

                    Log.d(TAG,  " SizeRR  " + read);
                     read = mmInStream.read(readBuffer);
                }


            } catch (IOException e) {
                break;
            }
        }
    }

Log.d (SizeRR 1) 读取 8 次

4

1 回答 1

0

InputStream.read() is designed to return an abstract int, so it will always print a number from 0-255.

Try instead the read(byte[] buffer) method, it writes buffer.length amount of data from the stream and copies the data straight to the array:

public void run() {

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {

            InputStream mmInStream = btSocket.getInputStream();
            byte[] readBuffer = new byte[8];
            mmInStream.read(readBuffer);

        } catch (IOException e) {
            break;
        }
    }
}
于 2013-08-24T23:31:59.767 回答