Android和Arduino之间的蓝牙数据丢失

时间:2015-05-26 17:37:16

标签: java android bluetooth byte buffer

直截了当 - 由于一些神秘的原因我的应用程序在接收InputStream时丢失了部分数据(String)。我在这里谈论蓝牙连接。大多数时候,我收到正确的字符串,但一旦进入缩短状态。这里最奇怪的是我将每个InputStream打印到我的ScrollView中,我可以告诉整个字符串都在那里......不过这里是代码:

@Override
public void run() {
    InputStream inputStream;

    try {
        inputStream = mBTSocket.getInputStream();
        while (!bStop) {
            byte[] buffer = new byte[256];
            int bytes;
            if (inputStream.available() > 0) {
                bytes = inputStream.read(buffer);
                final String strInput = new String(buffer, 0, bytes);;

                mTxtReceive.post(new Runnable() {
                    @Override
                    public void run() {
                        mTxtReceive.append(strInput);

                        int txtLength = mTxtReceive.getEditableText().length();
                        if (txtLength > mMaxChars) {
                            mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
                        }

                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                scrollView.fullScroll(View.FOCUS_DOWN);
                            }
                        });
                        }
                    });

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        weather = strInput.split(",");
                        mTxtHumidity.setText(weather[0]);
                        mTxtTemperatureDHT.setText(weather[1]);
                        mTxtPressure.setText(weather[2]);
                        mTxtLux.setText(weather[3]);
                        mTxtRainMM.setText(weather[4]);
                        mTxtRainDaily.setText(weather[5]);
                        mTxtWSKPH.setText(weather[6]);
                        mTxtWGKPH.setText(weather[7]);
                        mTxtWSAVG2.setText(weather[8]);
                        mTxtWGAVG10.setText(weather[9]);

                    }
                });
            }
            Thread.sleep(500);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

这里的问题是数组weather上的空异常,因为根据我的应用程序,我有时会访问超出边界的项目(weather长度大多数时间是6/7/8一旦出错)。应用程序在10%的时间内崩溃。

背后的原因是什么?

编辑:有时接收InputStream而不是接收56个字节,我得到33和22个

1 个答案:

答案 0 :(得分:0)

答案可以在这里找到:Android InputStream dropping first two bytes (modified BluetoothChat)

添加

try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

仅解决由于sleep方法导致Android和Arduino之间的非动态数据交换。事实证明,即使sleep(50)也适用于这种情况。由于某种原因,这个短sleep缓冲区永远不会被分割也不会丢失。如果编码不好,请在downvoting之前解释。