更新: 我真正的类看起来像这样,它的工作原理(它从onLocationChange方法敬酒我dis变量)。但是我无法在MainActivity中使用这个变量 - 它总是让我感觉到0.0 - 这个类有可能在某个时候破坏这个变量吗?requestLocation更新计数行走的米
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提供商计算米的米。而现在,我thinnking关于使用requestLocationUpdates也许这样:
int i;
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
and
public void onLocationChanged(Location location) {
i++
}
因此根据谷歌的引用,它应该自动更新我的INT I每个新一米。那就对了?或者,也许我认为错了?这看起来很容易计数米的旅行,但我不知道它会工作,它是否会准确......任何建议?
你可以看看更新吗? – bakusek
好吧,给我一分钟。 – tahsinRupam
为什么你必须使用'setDis()'?无论如何,'dis'的值在'onLocationChanged()'中改变。我建议你为你的活动实现'LocationListener'。 – tahsinRupam