【发布时间】:2014-04-07 21:07:38
【问题描述】:
由于手机或平板电脑上的文本文件,我正在尝试编写一个应用程序来记录 arduino 的输出。输出速率为 1kHz。我的应用程序基于 Blueserial 代码 (https://github.com/plastygrove/BlueSerial)。使用 arduino 蓝牙模块正确建立蓝牙连接,正确发送和接收命令,一切似乎都正常。但是,我将数据保存到的文件缺少数据块,通常每隔 200 毫秒左右(我的数据中包含毫秒时间戳),从而导致数据损坏。我一直在试图找出问题的根源,我认为它可能与 gc 有关,但此时我不知所措。这是将我的数据写入文件的代码:
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
while (!bStop) {
byte[] buffer = new byte[250];
int bytes = 0;
if (bis.available() > 0) {
bytes = bis.read(buffer);
strInput = new String(buffer, 0, bytes);
sb.append(strInput);
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
pw.print(strInput); // print buffer to the file buffer
pw.flush(); // flush buffer and force write to media
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear the string
pw.print(strInput); // write buffer to file buffer
pw.flush(); // force writing to file
pw.close(); // close print writer
try {
f.close(); // close file output stream
} catch (IOException e) {
e.printStackTrace();
}
}
sb.delete(0, sb.length()); strInput = "";
}
//Thread.sleep(100);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
这是我的文件 outputteam 和 printwriter 声明:
String strInput = null;
static PrintWriter pw = null;
static FileOutputStream f = null;
private StringBuilder sb = new StringBuilder();
我发送的数据格式如下:
24.330,-58,5,119,460\n
24.331,-86,25,-105,460\n
24.332,66,41,-145,460\n
24.333,90,-23,-85,4622,-7,119,460\n
24.524,6,-95,107,461\n
24.525,10,-7,-173,461\n
24.526,-22,33,103,461\n
在这个例子中你可以看到它在哪里跳过了一些数据。感谢您的帮助!
【问题讨论】:
-
你是对的 Keithrel,我已经添加了剩下的缺失类。在我的主要活动中,还有另外两个类,一个是 BtConnect 调用
mReadThread = new ReadInput();在蓝牙通信建立后启动输入阅读器,另一个是 BTDisconnect 在用户选择断开连接时调用mReadThread.stop();。
标签: android bluetooth inputstream printwriter