我的USB主机正在接收传感器数据,并且每200毫秒更新一次。我想每200毫秒在我的Android应用程序中读取这些数据。我能够使用bufferreader读取它,它会读取数据一段时间然后挂起。这不一致。我是新手,可能是我没有以正确的方式做到这一点。请在下面找到我的代码并告诉我您的建议。提前谢谢。
public void startProcessOne()
{
new CountDownTimer(110,100)
{
@Override
public void onTick(long millisUntilFinished)
{
StringBuilder text = new StringBuilder();
line = "";
try {
FileReader in = new FileReader("/mnt/udisk/TEST.TXT");
BufferedReader br = new BufferedReader(in);
int i=0;
char[] buf = new char[10000];
while((i = br.read(buf,i,100))!= -1)
{
String h = new String(buf);
text.append(h);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
TxtRead.setText(text.toString());
}
@Override
public void onFinish()
{
startProcessOne();
}
}.start();
}
答案 0 :(得分:0)
TxtRead.setText(text.toString());
此行导致问题。您无法从后台线程触摸UI元素。您应该在UI /主线程中运行这些代码。
在您的情况下,我个人更喜欢使用Java线程。因此,创建一个后台线程以定期运行。如果您需要从该后台线程运行UI方法。您可能需要一个附加到主线程的处理程序。
// Instantiate a handler in UI thread
final Handler handler = new Handler();
new Thread(new Runnable(){
// Once you're done and want to break the loop, just set this boolean
private boolean stopped = false;
@Override
public void run(){
while(!stopped) {
// Read from the file
// Whenever you need to update an UI element,
// you should wrap it inside this runnable object
handler.post(new Runnable(){
@Override
public void run(){
// Update UI
TxtRead.setText("new_text");
}
})
try {
// This thread will sleep for 9 seconds
Thread.Sleep(9000);
} catch(Exception e){}
}
}
}).start();