【发布时间】:2017-04-19 09:00:20
【问题描述】:
更新: 我真正的课程看起来像这样并且它有效(它从 onLocationChange 方法向我敬酒 dis 变量)。但是我无法在 MainActivity 中访问这个变量 - 它总是给我 0.0 - 这个类是否有可能在某个时候破坏这个变量?
public class GPStracker implements LocationListener {
Context context;
double plat;
double plon;
double clat;
double clon;
public double dis;
public GPStracker(Context c) {
context = c;
}
public Location getlocation() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSenabled;
isGPSenabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSenabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return location;
} else {
Toast.makeText(context, "Proszę włączyć GPS", Toast.LENGTH_LONG).show();
}
return null;
}
@Override
public void onLocationChanged(Location location) {
clat = location.getLatitude();
clon = location.getLongitude();
if (clat != plat || clon != plon) {
dis += getDistance(plat, plon, clat, clon);
plat = clat;
plon = clon;
setDis(dis);
}
Toast.makeText(context, String.valueOf(dis), Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
public double getDistance(double lat1, double lon1, double lat2, double lon2) {
double latA = Math.toRadians(lat1);
double lonA = Math.toRadians(lon1);
double latB = Math.toRadians(lat2);
double lonB = Math.toRadians(lon2);
double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB - lonA)) +
(Math.sin(latA) * Math.sin(latB));
double ang = Math.acos(cosAng);
double dist = ang * 6371;
return dist;
}
public double getDis() {
return dis;
}
public void setDis(double dis) {
this.dis = dis;
}
}
我想问(也许那是一个愚蠢的问题),但我正在尝试使用 gps 提供商计算行程米数。现在我正在考虑以这种方式使用 requestLocationUpdates:
int i;
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
and
public void onLocationChanged(Location location) {
i++
}
所以根据谷歌的参考资料,它应该自动更新我的 int i 每一新的一米。这是正确的?或者我想错了?这看起来很容易计算行程米,但我不确定它是否有效以及它是否准确......有什么建议吗?
【问题讨论】:
标签: java android android-gps