我试图制作一个从Arduino通过蓝牙接收字符串的应用程序。
其格式为"#100.23+123.12+90.45+101.20~
,+
是四个双数之间的分隔符,以#开头,以〜结尾。
我已经按照教程here进行了操作。一切似乎都没问题,但大多数情况下,四个Textview
不会像我为他们指定的那样更新值。
这是更新Textview
的代码,它依赖于onCreate()
函数。
有时它会更新(很少),而且大部分时间它都不会更改。 请帮帮我,我对android有一点了解。感谢
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
//sensorView0.setText("Temp111111");
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
recDataString.append(readMessage); //keep appending to string until ~
int startOfLineIndex = recDataString.indexOf("#");
int endOfLineIndex = recDataString.indexOf("~",startOfLineIndex); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(startOfLineIndex, endOfLineIndex); // extract string
if (dataInPrint.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
int startPos =1;
int endPos = dataInPrint.indexOf("+");
String sensor0 = dataInPrint.substring(startPos, endPos); //get sensor value from string between indices 1-5
startPos =endPos +1;
endPos = dataInPrint.indexOf("+",endPos+1);
String sensor1 = dataInPrint.substring(startPos, endPos); //same again...
startPos =endPos +1;
endPos = dataInPrint.indexOf("+",endPos+1);
String sensor2 = dataInPrint.substring(startPos, endPos);
startPos =endPos +1;
endPos = dataInPrint.indexOf("+",endPos+1);
String sensor3 = dataInPrint.substring(startPos, endPos);
sensorView0.setText(" Heart Rate = " + sensor0 + "bpm"); //update the textviews with sensor values
sensorView1.setText(" Blood = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
dataInPrint = " ";
}
}
}
};