如何通过Android蓝牙串行RFCOMM将串行通信转储为文件

时间:2019-03-26 06:58:55

标签: java android bluetooth serial-port rfcomm

我的Android应用通过桌面应用通过蓝牙接收串行通信。我无法控制该桌面应用程序在做什么。

使用Google BluetoothChat示例代码(https://github.com/googlesamples/android-BluetoothChat)。我设法使其正常工作,并且在某种程度上,我可以简单地将字节放入我的android应用中并写入文件。

但是,代码功能类似于

1-Android收听

2-PC发送数据,Android接受连接读取数据并写入文件

3-阅读时,Android遇到异常(客户端关闭连接?)并关闭连接

4-回到第一,并听接下来的几个字节

我的问题是我需要知道该过程何时结束以处理文件并在UI中显示一些结果。

代码是这个文件

https://github.com/googlesamples/android-BluetoothChat/blob/master/Application/src/main/java/com/example/android/bluetoothchat/BluetoothChatService.java

特别是

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

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

                // ==> This is where I wrote to file
                // ==> Standard Android Java code to write 
                // ==> to output file stream

                // Send the obtained bytes to the UI Activity
                // ==> Commented out because this can not be done here
                // ==> NEED TO BE DONE WHEN ALL DATA IS READ
                // mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                //      .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

预计Android RFCOMM或Bluetooth Communication中应该有一种方法可以表明客户端已经完成了所有通信的发送。

以前,我尝试使用IoException来向UI发出从PC读取数据的信号。那是一场灾难,因为出于某种原因,异常只会在通信开始时发生。而且我不知道为什么我的代码仍然会继续写入文件。

我要重复一遍,我对PC /台式机应用程序没有任何控制权。因此,请勿提出任何涉及改变桌面应用程序操作或发送数据方式的建议。

需要在Android端处理此问题。

1 个答案:

答案 0 :(得分:0)

除非拥有规则和/或某种协议并开始解析您身边的数据,否则您永远无法确定远端是否已完成要发送的数据。

添加/创建带有标头和长度字段的简单协议,使您能够接收,而且知道在接收循环中会发生什么。

根据经验;永远不要以为您一次读取就可以获得整个数据包。相反,在最终处理该数据并提取符合您的规格的完整“数据包”之前,请对接收到的数据进行缓冲并允许多次读取。