繁体   English   中英

位置更新提供用于计算距离的随机数

[英]Location Updates giving random numbers for calculating distance

我目前正在尝试在 Android Studio 上开发一个跑步跟踪器,我正在使用普通技术来获取距离,然后将其转换为英里而不是米,我正在服务中进行。 但是,当我开始模拟路线时,它开始喷出随机的长数字。 我知道这与我如何使用 distanceTo() 计算距离有关,但不知道如何解决它。 没有发布整个代码,但相关部分很糟糕

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("G53", "onCreate called");
        locationListener = new MyLocationListener();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 5, locationListener);
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            oldLocation = location;

        } catch (SecurityException e) {
            Log.d("g53mdp", e.toString());
        }
    }

 public double getDistance() {

        if(running) {
            distance = distance * 0.000621371192;
            Log.d("tag", " " + distance);
            return distance;
        }
        return 0;

    }

    public void startExercise() {
        Log.d("tag", "startExercise called");
        startTime = System.currentTimeMillis();
        stopTime = 0;
        running = true;
        distance = 0;
    }

    public void stopExercise() {
        Log.d("tag", "stopExercise called");
        running = false;
        startTime = 0;
    }

    public class MyLocationListener extends Binder implements LocationListener, IInterface {

        @Override
        public void onLocationChanged(Location location) {
        
            if(running) {
                distanceInMetres = oldLocation.distanceTo(location);
                if (distanceInMetres < 10) {
                    Log.i("DISTANCE", "Values too close, so not used.");
                } else {
                    distance += distanceInMetres;
                    oldLocation = location;
                }
            }
        }

Logcat 中的 output 看起来像这样

在此处输入图像描述

我有2个想法。

我阅读了您的代码,您可以将英里转换为米。

1.-我认为问题是您在 2 种或多种方法中重新利用距离变量,从而造成溢出。

你在这里增加了一个距离。

 distance += distanceInMetres;

那是完美的,但是然后您读取该变量并为它们分配一个新值

public double getDistance() {

        if(running) {
            distance = distance * 0.000621371192;
            Log.d("tag", " " + distance);
            return distance;
        }
        return 0;

    }

所以我建议你把getDistance()改成

public double getDistance() {
        if(running) {
            return distance * 0.000621371192;
        }
        return 0;
    }

这样,您就无需重新分配值。

2.- 另一个可能的问题可能是并发问题,但您需要发布更多关于您的代码的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM