【发布时间】:2017-01-14 23:21:53
【问题描述】:
我对java很陌生,我有一个任务来实现心跳机制来监控BT芯片的活跃度。
BT 芯片每 5 秒通过 uart 接口不断发送一条空消息(只有消息 ID,没有内容),必须由 java 模块读取。如果没有收到消息,则假设芯片上的固件已失效,需要重置,java 模块可以通过切换 GPIO 来做到这一点。
负责从 uart 读取的模块被实现为扩展线程的类。我尝试使用 android.os.CountdownTimer,但它不起作用。它抛出这个错误:
AndroidRuntime: java.lang.RuntimeException: 无法在未调用 Looper.prepare() 的线程内创建处理程序
Java 中用于实现此类需求的最佳机制是什么?
/*Start timer for 5s for receiving heartbeat*/
mTimer=new CountDownTimer(5000,1000) {
@Override
public void onTick ( long l){
}
@Override
public void onFinish () {
Log.e(TAG, "Nothing received for 5s, missed heartbeat, reset BT chip");
try {
resetBTChip(false);
} catch (InterruptedException e) {
Log.e(TAG, "Can't reset the chip");
return;
}
}
};
mTimer.start();
/*Check the message and deal with timer*/
if(HEART_BEAT.getCode()==opcode) {
mTimer.cancel(); /*Restart the timer on heart-beat event*/
mTimer.start();
Log.e(TAG, "Got HEART BEAT");
continue;
} else {
Log.e(TAG, "Got Something else, handle the message");
mTimer.cancel(); /*Restart the timer on any event*/
mTimer.start();
}
【问题讨论】:
标签: java android multithreading