简体   繁体   中英

Bluetooth receive data

I have setup a socket to receive data from a bluetooth device. The receive buffer is is set up to gather 8 bytes of data before exiting the thread but the buffer does not advance to store next byte of data. I set buffer to 8 and loop until buffer is full.

      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) reads 8 times

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM