Ich habe ein Problem mit aktuellen Standort bekommen, weil, ich habe in meinem MainActivity den Hörer:bekommen aktuellen Standort android
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
new MyLocationListener()
);
Und ich habe eine zweite Aktivität, wo ich würde, wenn ich auf die Schaltfläche klicken, berechnen Entfernung von meinem Standort und gPS-Koordinaten, dass ich mit distanceTo
und return true passieren wird, wenn der Abstand beetween 0 und 200. So habe ich eine Funktion in SecondActivity
private boolean checkCoordinate(String gps) {
LocationManager lm = (LocationManager) getSystemService(App.getContext().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return false;
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double currentLongitude = location.getLongitude();
double currentLatitude = location.getLatitude();
Location loc1 = new Location("");
loc1.setLatitude(currentLatitude);
loc1.setLongitude(currentLongitude);
String[] sep = gps.split(",");
double latitude = Double.parseDouble(sep[0]);
double longitude = Double.parseDouble(sep[1]);
Location loc2 = new Location("");
loc2.setLatitude(latitude);
loc2.setLongitude(longitude);
float distanceInMeters = loc1.distanceTo(loc2);
if(distanceInMeters < 200){
return true;
}else{
return false;
}
}
Aber das Problem ist, dass manchmal und vielleicht, wenn ich meine Lage, die Funktion nicht ändern:
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return null, und ich verstehe nicht, wie meine aktuelle Position wissen, weil ich bereits requestLocationUpdates gesetzt habe. so wie kann ich meinen aktuellen Standort wissen?
Ja Ich habe festgestellt, dass das Problem nicht Startup-GPS-Anbieter ist, und für jetzt habe ich "vorübergehend gelöst" mit "if (location == null) {location = lm.getLastKnownLocation (LocationManager.NETWORK_PROVIDER); } '. Aber ich weiß nicht, ob eine schlechte Praxis oder wenn könnte ein Problem tun, aber scheint Arbeit auch der Standort ist weniger Genauigkeit – LorenzoBerti
obwohl dies viel seltener auftritt, Netzwerkstandort kann auch fehlen. –
Ok danke, also habe ich 'requestSingleUpdate' anstatt' requestLocationUpdates' oder 'requestSingleUpdate' in Meine Funktion' checkCoordinate' verwendet. – LorenzoBerti