我有一个计步器应用程序,我在其中运行一个服务,计算所采取的步骤,然后向片段发送广播,然后在片段上更新.步数正常,但我想根据步骤计算速度.这就是我现在正在尝试的.
获取步数的接收器:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
所以我正在做的是,一旦我开始得到步骤,我看到变量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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以在这里我只检查两者是否都是空的,我取值并计算时间差.这里的问题有时它不能正确计算速度.更大的问题是如果用户停止,速度保持不变并且不会降至零.
有没有更好的方法来进行速度计算?
小智 10
由于你只是计算步数而且想用步数计算速度,我假设你不想用GPS计算速度,或者你想提供备用速度计数器,如果没有GPS.
你可以通过这样做开始一个新线程
int interval=1*1000; //specifying interval to check steps
Handler.postDelayed(mySpeedChecker(),1000);
Run Code Online (Sandbox Code Playgroud)
您需要为每个步骤执行此操作
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
}
Run Code Online (Sandbox Code Playgroud)
此外,当GPS可用时计算用户步幅是个好主意,因此,当用户使用GPS时,可以通过找出所覆盖的距离/借助GPS获取的步数来计算步长,这将有助于您的系统借助于所采取的步骤精确计算用户所覆盖的距离.