为什么 getSpeed() 在 android 上总是返回 0getSpeed、android

2023-09-07 03:54:16 作者:愿与君执手

我需要通过 GPS 获取速度和航向.但是,我从 location.getSpeed() 获得的唯一数字是 0 或有时不可用.我的代码:

I need to get the speed and heading from the gps. However the only number i have from location.getSpeed() is 0 or sometimes not available. my code:

        String provider = initLocManager();
    if (provider == null)
        return false;
    LocationListener locListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location, interval, startId);
            Log.i(getString(R.string.logging_tag), "speed =" + location.getSpeed());
        }

        public void onProviderDisabled(String provider){
            updateWithNewLocation(null, interval, startId);
        }

        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    _locManager.requestLocationUpdates(provider, interval,  DEFAULT_GPS_MIN_DISTANCE, locListener);


    private String initLocManager() {
    String context = Context.LOCATION_SERVICE;
    _locManager = (LocationManager) getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(true);
    criteria.setSpeedRequired(true);
    criteria.setCostAllowed(true);
    //criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = _locManager.getBestProvider(criteria, true);

    if (provider == null || provider.equals("")) {
        displayGPSNotEnabledWarning(this);
        return null;
    }

    return provider;
}

我尝试玩标准但没有成功.有谁知道问题出在哪里?

I tried to play the Criteria with but no success. Does anyone have an idea what is the problem?

推荐答案

location.getSpeed() 仅返回使用 location.setSpeed() 设置的内容.这是您可以为位置对象设置的值.

location.getSpeed() only returns what was set with location.setSpeed(). This is a value that you can set for a location object.

要使用 GPS 计算速度,您需要做一些数学运算:

To calculate the speed using GPS, you'll have to do a little math:

Speed = distance / time

所以你需要这样做:

(currentGPSPoint - lastGPSPoint) / (time between GPS points)

全部转换为 ft/sec,或者您想要显示的速度.这就是我在制作跑步者应用时的做法.

All converted to ft/sec, or however you want to show the speed. This is how I did it when I made a runner app.

更具体地说,您需要计算绝对距离:

More specifically, you'll need to calculate for absolute distances:

(sqrt((currentGPSPointX - lastGPSPointX)^2) + (currentGPSPointY - lastGPSPointY)^2)) / (time between GPS points)

创建一个新的 TrackPoint 类或其他东西可能会有所帮助,它将 GPS 位置和时间保存在里面.

It might help to make a new TrackPoint class or something, which keeps the GPS location and time it was taken inside.