我有一个计步器应用程序,我在其中运行一项服务,该服务计算所采取的步数,然后向 fragment 发送广播,然后在 fragment 上更新该 fragment 。计步工作正常,但我想根据步数计算速度。这是我现在正在尝试的。
获取步数的接收方:
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int steps = intent.getIntExtra(StepCounterService.STEP_INCREMENT_KEY, 0);
if (firstStepTime.equals("0")) {
firstStepTime = intent.getStringExtra(StepCounterService.TIME_STAMP_KEY);
} else if (secondStepTime.equals("0")) {
secondStepTime = intent.getStringExtra(StepCounterService.TIME_STAMP_KEY);
} else {
firstStepTime = secondStepTime;
secondStepTime = intent.getStringExtra(StepCounterService.TIME_STAMP_KEY);
}
updateAllUI(steps);
}
};
所以我正在做的是,一旦我开始获取步数,我就会查看变量 firstStepTime
是否为空。如果是,我将时间保存在 firstStepTime
变量中。在下一步中,我会查看 secondStepTime
是否为空,如果是,我将该时间保存在 secondStepTime
变量中。
现在,对于接下来的步骤,这两个都已更新。
public void updateAllUI(int numberOfSteps) {
if (!(firstStepTime.equals("0")) && !(secondStepTime.equals("0"))) {
try {
Calendar c = Calendar.getInstance();
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
timeDifference = timeFormat.parse(secondStepTime).getTime() - timeFormat.parse(firstStepTime).getTime();
speed = (float) ((0.0254 / (timeDifference * 0.001)) * 3.6);
} catch (Exception e) {
timeDifference = 0;
speed = 0;
}
textview.settext(speed +"Km/h);
}
}
所以在此我只是检查两者是否不为空,我取值并计算时间差。这里的问题是有时它不能正确计算速度。一个更大的问题是,如果用户停下来,速度会保持不变,不会降至零。
有没有更好的方法来计算速度?
最佳答案
由于您只计算步数并且只想计算所走步数的速度,我假设您不希望使用 GPS 计算速度,或者如果 GPS 不存在,您希望提供备用速度计数器。
您可以通过以下方式开始一个新线程
int interval=1*1000; //specifying interval to check steps
Handler.postDelayed(mySpeedChecker(),1000);
您需要对所采取的每一步执行此操作
public void mySpeedChecker(){
// assuming steps taken stored in a global variable
// and there is one more variable which is updated by this function
// to store number of steps before as global variable to calculate number of steps in time interval.
// this should check if another step has been taken in the interval to check
// if stepsTaken>0 then speed is not zero and you'll know how much steps are taken
// if zero steps are taken then speed is zero
// also it will tell you number of steps taken in last second
// so you can use this to calculate and update speed
// increase the interval for high accuracy but lower frequency of updates
}
此外,在 GPS 可用时计算用户步幅是个好主意,因此,每当用户使用 GPS 时,都可以通过在 GPS 的帮助下找出覆盖的距离/步数来计算步长,这将借助步数,帮助您的系统准确计算用户走过的距离。
关于java - 如何根据步数计算速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441054/