2

我遇到了蓝牙问题,我的连接已经建立,我可以向我的模块发送数据,但接收总是拆分我的字节数组,来自模块的消息在第一个字节和消息的其余部分分开,所以不是单个消息我收到两个。我使用了蓝牙聊天示例。

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[100];

        int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(ActivityTrafficSignChooserUpperSign.MESSAGE_READ, bytes, bytes, buffer)
                        .sendToTarget();
                //Log.d(TAG, bytes);
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

这是我活动的一部分:

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {


            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                readMessage = new String(readBuf, 0, msg.arg1);
                Toast.makeText(getApplicationContext(), readMessage, Toast.LENGTH_SHORT).show();

                break;
         }}
4

0 回答 0