为什么 getSpeed() 在 android 上总是返回 0 [英] why getSpeed() always return 0 on android

查看:19
本文介绍了为什么 getSpeed() 在 android 上总是返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过 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.

这篇关于为什么 getSpeed() 在 android 上总是返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆