【问题标题】:onLocationChange() not getting called? Calculate Distance Travelled -AndroidonLocationChange() 没有被调用?计算行驶距离 - Android
【发布时间】:2013-07-10 17:05:54
【问题描述】:

我有这个代码:

Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;

onLocationChanged:

@Override
public void onLocationChanged(Location location) 
{
    oldLocation.set(newLocation);
    startactivity();
    distanceTravelled+=newLocation.distanceTo(oldLocation);
    String stringDistance= Float.toString(distanceTravelled);
    TextView distance = (TextView) findViewById(R.id.textDistance);
    distance.setText(stringDistance);
}

开始活动:

public void startactivity() 
{
    GPSTracker gps = new GPSTracker(Live.this);

    if(gps.canGetLocation())
    {
        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();
        Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

        newLocation.setLatitude(latitude);
        newLocation.setLongitude(longitude);    
    }
    else
    {
        gps.showSettingsAlert();
    }

}

GPSTracker 是一个单独的类,它获取当前的纬度和经度(它工作正常!)。

GPS 更新至少。距离 5 米和分钟。时间 5 秒。

这是我的完整 GPSTracker 课程:GPSTracker.java

我在 manifest 中添加了三个权限:fine、coarse 和 internet。

我的问题是 onLocationChanged 中的文本视图永远不会改变。

有什么问题?是 onLocationChanged 没有被调用还是存在一些逻辑错误(距离始终保持为零)?

以及如何解决这个问题?

【问题讨论】:

    标签: java android eclipse gps location


    【解决方案1】:

    你的功能是

    public void onLocationChanged(Location location) 
    

    但是您没有在函数的任何地方使用该参数。 看起来你应该添加

    newLocation.set(location);
    

    在函数的第一行之后。

    此时您正在计算起点与自身之间的距离,并且始终为 0。

    【讨论】:

    • 逻辑上看起来是正确的,你认为它会起作用吗?我现在无法测试它。每当位置发生变化时,textView 会更新吗?我还需要调用那个 startactivity 吗?
    • 我认为你不需要在onLocationChanged中调用startactivity(),开始活动一次就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多