我正在开发一个Android应用程序以从Arduino接收数据。
我正在从Arduino收集湿度,温度和距离数据,并使用HC-06传输到Android应用程序。我想在不同的TextView中显示每个数据的值。以下是我的代码:
Adruino:
...
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
...
distance = duration*(speedofsound/10000)/2;
BT.print("h");
BT.print(humidity);
BT.print("t");
BT.print(temperature);
BT.print("d");
BT.print(distance);
BT.print("e");
Android Studio:
...
String humidity, temperature, distance;
...
TextView textView,textView2,textView3;
...
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
textView3 = (TextView) findViewById(R.id.textView3);
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes,"UTF-8");
handler.post(new Runnable() {
public void run()
{
//textView.append(string);
humidity=string.substring(string.indexOf("h")+1,string.indexOf("t"));
temperature=string.substring(string.indexOf("t")+1,string.indexOf("d"));
distance=string.substring(string.indexOf("d")+1,string.indexOf("e"));
textView.setText(humidity);
textView2.setText(temperature);
textView3.setText(distance);
}
});
}
}
catch (IOException ex)
{
stopThread = true;
}
}
}
});
thread.start();
}
发生错误,应用程序强制停止。有人可以帮我解决这个问题吗?