Android java开发时加速到

时间:2011-09-28 06:30:32

标签: time acceleration

如何计算加速到100kmh的时间? 好吧,当!location.hasSpeed()为true时,我注册了一个位置监听器,将位置的时间存储到变量中。当速度达到给定速度时,在这种情况下,100km / h(27.77 m / s),我从位置的位置减去,结果我除以1000.

这是“伪代码”

    @Override
    public void onLocationChanged(Location currentLoc) {

        // when stop reseted, when start reset again
        if (isAccelerationLoggingStarted) {
            if (currentLoc.hasSpeed() && currentLoc.getSpeed() > 0.0) {
                // dismiss the time between reset to start to move  
                startAccelerationToTime = (double) currentLoc.getTime();
            }
        }

        if (!currentLoc.hasSpeed()) {
            isAccelerationLoggingStarted = true;
            startAccelerationToTime = (double) currentLoc.getTime();
            acceleration100 = 0.0;
        }

        if (isAccelerationLoggingStarted) {
            if (currentLoc.getSpeed() >= 27.77) {
                acceleration100 = (currentLoc.getTime() - startAccelerationToTime) / 1000;
                isAccelerationLoggingStarted = false;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我在这里看到的主要问题是每当设备移动时,startAccelerationToTime都会重置。 (第一个if仅检查是否有移动;它不会检查是否已记录开始时间。

我根本看不到isAccelerationLoggingStarted的位置 - 速度和变量本身可以稍微清理一下,以明确下一步应该是什么。

您的伪代码可能应该类似于:

if speed is 0
    clear start time
else if no start time yet
    start time = current time
    clear acceleration time
else if no acceleration time yet, and if speed >= 100 mph 
    acceleration time = current time - start time

在Java中,这看起来像......

long startTime = 0;
double accelerationTime = 0.0;

@Override
public void onLocationChanged(Location currentLoc) {

    // when stopped (or so slow we might as well be), reset start time
    if (!currentLoc.hasSpeed() || currentLoc.getSpeed() < 0.005) {
        startTime = 0;
    }

    // We're moving, but is there a start time yet?
    // if not, set it and clear the acceleration time
    else if (startTime == 0) {
        startTime = currentLoc.getTime();
        accelerationTime = 0.0;
    }

    // There's a start time, but are we going over 100 km/h?
    // if so, and we don't have an acceleration time yet, set it
    else if (accelerationTime == 0.0 && currentLoc.getSpeed() >= 27.77) {
        accelerationTime = (double)(currentLoc.getTime() - startTime) / 1000.0;
    }
}

现在,我不确定位置听众是如何工作的,或者他们在移动时多久会通知您。所以这可能只是半工作。特别是,当你不动时,onLocationChanged可能不会被调用;您可能需要请求更新(可能通过“重置”按钮或其他东西)或设置某些参数以触发速度== 0时发生的事情。