我正在开发 android 中的应用程序。我正在尝试从后台线程将数据更新到 UI。但是,由于某些原因,它不起作用。任何人都可以找出错误或提出更好的解决方案吗?我使用 Thread 从蓝牙套接字读取数据并使用 RunOntheUI 更新 UI。这是代码:
socket = belt.createRfcommSocketToServiceRecord(UUID_SECURE);
socket.connect();
stream = socket.getInputStream();
// final int intch;
Thread timer2 = new Thread() { // Threads - do multiple things
public void run() {
try {
// read data from input stream if the end has not been reached
while ((intch = stream.read()) != -1) {
byte ch = (byte) intch;
b1.append(ByteToHexString(ch) +"/");
decoder.Decode(b1.toString());
runOnUiThread(new Runnable() {
public void run()
{
// update the uI
hRMonitor.SetHeartRateValue((int) decoder.GetHeartRate());
}
});
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}};
timer2.start();