Android: Aufruf Methode in Abständen, um die neuesten Standort Koordinaten
Hi! Ich hatte einen Locationlistener und Manager in meiner Mainactivity-Klasse, aber ich dachte, das wäre eine ziemlich schlechte Lösung, da ich die Standortfunktionalität in einer anderen Klasse haben möchte, weil ich möchte, dass der Hörer Intents überdauert.
Ich habe nur etwa 10 Stunden Erfahrung in der Android-Programmierung so dass diese für einige Leute schrecklich aussehen könnte;)
Hauptaktivität
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xxx);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
location = new RetrieveLocation(this);
checkForPermission();
...
//I want this method to call location.getCoordinates() in 1 second intervals
public void updateMap() {
if (location.hasFoundLocation()) {
enableButton();
marker.setPosition(location.getCoordinates());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(location.getCoordinates(), 16));
}
else {
disableButton();
}
}
public void checkForPermission()
{
if (Build.VERSION.SDK_INT >= 23) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
}, 10);
}
else {
location.listen();
updateMap();
}
}
So retrieveLocation Klasse grundsätzlich aktualisiert nur die Benutzerposition wenn das Gerät bewegt wird.
Also ich möchte die Koordinaten der mainActivity Klasse jede Sekunde und aktualisieren Sie die Markierung auf Google Maps.RetrieveLocation
public class RetrieveLocation
{
private LocationManager locationManager;
private LocationListener locationListener;
private LatLng _location;
private Context context;
public RetrieveLocation(Context context)
{
this.context = context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void listen()
{
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
_location = new LatLng(location.getLatitude(), location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
};
//noinspection ResourceType
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}
...
public LatLng getCoordinates()
{
if(_location != null)
return _location;
else
return new LatLng(0,0);
}
ich vor ziemlich viel gesucht haben diesen Beitrag zu schreiben
Ah süß, wie könnte ich das verpasst haben? Vielen Dank! – Awozo