我有这个代码:
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;
位置更改:
@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);
}
启动 Activity :
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
我在 list 中添加了三个权限:fine、coarse 和 internet。
我的问题是 onLocationChanged 内的 textview 永远不会改变。
有什么问题吗? onLocationChanged 是否没有被调用或者存在一些逻辑错误(距离始终保持为零)?
如何解决这个问题?
最佳答案
你的函数是
public void onLocationChanged(Location location)
但您没有在函数中的任何地方使用该参数。 看起来你应该添加
newLocation.set(location);
在函数的第一行之后。
此时您正在计算起点与其自身之间的距离,并且该距离始终为 0。
关于java - onLocationChange() 没有被调用?计算行驶距离 -Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17565941/