Data Transmisison error using SPP over Bluetooth on Android

不想你离开。 提交于 2019-11-29 23:21:19

The fix for the solution was to create the string in the connected thread, directly after calling read() on the InputStream, and then passing the string back to the main thread for display. For whatever reason, passing the byte array between threads led to significant repetition and data loss.

Modified run() code:

    public void run() {
        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                String readMessage = new String(buffer, 0, bytes);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, readMessage)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

And the handler reception:

        case MESSAGE_READ:
            // Read in string from message, display to mainText for user
            String readMessage = (String) msg.obj;
            if (msg.arg1 > 0) {
                mainText.append(readMessage);
            }

This error is because the object reference is passed to the UI, If you copy the byte array(buffer) to another byte array it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!