【问题标题】:Handling of periodic heart-beat messages from BT chip处理来自 BT 芯片的周期性心跳消息
【发布时间】: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


    【解决方案1】:

    你可以做一个runnable和一个handler。处理程序有一个 postdelay 函数,允许您指定在运行 runnable 之前等待多长时间。他们还可以删除/取消计时器。这就是我以前做心跳的方式。如果倒计时不起作用,您可以尝试一下。

    因此,runnable 将负责重置功能。你会使用你当前的计时器。如果您再次收到心跳,您只需取消当前的可运行,并使用 postdelay 函数将其重新添加以重新启动计时器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      相关资源
      最近更新 更多