蓝牙InStream缺少第一个字符/拆分字符串

时间:2017-11-08 08:43:38

标签: java android bluetooth android-bluetooth

我从蓝牙的流输入中收到一个字符串,主要问题是字符不是以完整字符串形式出现的。由于某种原因,有时会分别读取第一个字符或分别读取最后几个字符。

我一直在寻找解决方案的时间。我甚至试过sleep(),这是一个显然有效的黑客,但不是所有的时间。我需要它一直工作。

有人说bufferReader或dataInputStream更好吗?

bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
        if (msg.what == handlerState) {                                                     //if message is what we want

            String readMessage = (String) msg.obj;                                          // msg.arg1 = bytes from connect thread
            sensorView0.setText(readMessage);
                if(readMessage.equals("Alarm")){
                    Intent buzz= new Intent(MainActivity.this,backgroundService.class);
                    MainActivity.this.startService(buzz);
                }
        }
        }
    };

// --------------------------------------------- ------------------------------------------

public void run() {
        byte[] buffer = new byte[512];
        int bytes;

        // Keep looping to listen for received messages
        while (true) {
            try {

                bytes = mmInStream.available();
                while( bytes> 0 ){
                    bytes = mmInStream.read(buffer);            //read bytes from input buffer
                    String readMessage = new String(buffer, 0, bytes);
                    // Send the obtained bytes to the UI Activity via handler

                    bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                }
            } catch (IOException e) {
                break;
            }
        }
    }

EDIT ---------------------------------------------- ----------------------------

bluetoothIn = new Handler() {
    public void handleMessage(android.os.Message msg) {
    if (msg.what == handlerState) {
        String readMessage = (String) msg.obj;
        //will keep combining the chars until end-of-line
        befEndLine = befEndLine + readMessage;
        // determine the end-of-line
        int endOfLineIndex = befEndLine.indexOf("\n");

        if (endOfLineIndex != -1) { //check if character is there if not skip

            String dataInPrint = befEndLine.substring(0, endOfLineIndex);    // extract string

            received.setText(dataInPrint);

            //Clear the data held in string
            befEndLine = "";

        }
    }

    }
};

0 个答案:

没有答案