该应用程序记录气压。为了保持应用程序运行(或向用户显示运行),该活动将启动并绑定到专用后台服务。到目前为止一切顺利,活动可能会被操作系统关闭,但服务仍保持运行,当活动重新启动时,它会重新连接到服务并从服务中提取数据。但是,即使服务正在运行,如果活动未处于焦点状态或设备处于睡眠状态,服务中的倒计时器会在几分钟或几小时后停止。
无法使用作业计划程序,因为它会在需要时执行作业,而不是按照固定的时间表执行作业。 CountDownTimer 和 Handler 与实时 ISR 的工作方式类似。
关于保持服务计时器运行有什么建议吗?
Service类中的onStartCommand():
int TestVar = -1; //[sic]
Date CurTime = Calendar.getInstance().getTime(); //current time since 1970-01-01 (mS)
long StartTime = CurTime.getTime(); //service start time (mS from 1970-01-01)
CountDownTimer GpTimer = new CountDownTimer(60*60*24*365*10*1000, 10000) {
public void onTick(long mSleft) { //Every 10 Sec...
CurTime = Calendar.getInstance().getTime(); //current time (mS from 1970-01-01)
int RunTime = (int) ((CurTime.getTime() - StartTime) / 10000);
TestVar++; //testing only, increment counter every 10 seconds ...when it does
NotifBuilder.setContentText("Realtime: " + RunTime + ", Tics: " + TestVar);
NotifManager.notify(FOREGROUND_ID, NotifBuilder.build());
}
public void onFinish () {} //decade is over, how time flies
}.start();