I’m using the following code in my app, from tutorials etc., to get the best possible location fix from the GPS (or if GPS not on, network), which I then display in a text field.
crit = new Criteria();
context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(context);
crit.setAccuracy(Criteria.ACCURACY_FINE);
crit.setPowerRequirement(Criteria.POWER_LOW);
crit.setAltitudeRequired(false);
crit.setBearingRequired(false);
crit.setSpeedRequired(false);
crit.setCostAllowed(false);
try {
bestProvider = locationManager.getBestProvider(crit, true);
loc = locationManager.getLastKnownLocation(bestProvider);
locationManager.requestLocationUpdates(bestProvider, 0, 0,
new GeoUpdateHandler());
} catch (java.lang.RuntimeException run) {
Toast.makeText(getBaseContext(),
"Waiting for location fix...", Toast.LENGTH_SHORT).show();
}
My problem is moving between locations. I start using my app in Norfolk and get the location OK. The next day, I’m in Cornwall (100’s mile apart) and when I switch on my app (it should have been closed/destroyed by Android in this time), it is still showing me the Norfolk location. I find that if I then exit my app and start it again, it then picks up the new location. I can do this easily, but my users are finding it a real pain.
My assumptions were that if GPS/network is available, then I start the app, the LOC is created from last known location, then locationManager updates instantly (which should update LOC instantly?) using:
public class GeoUpdateHandler implements LocationListener {
public void onLocationChanged(Location location) {
loc = location;
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
Clearly this update isn’t happening.
Can anyone tell me if my code is stupid, or advise on a better way to make sure I’m always dealing with current location? Thanks. Apologies if this is answered, difficult to find in amongst all the posts on locations & requestLocationUpdates tags.
After discussion in chat I suggested the following:
You need to call
requestLocationUpdates()and then show the user a dialog saying something like ‘getting your location’. At some time later, you should get a callbackonLocationChanged()with an up-to-date location. At that point you can dismiss the dialog and update the text fields and whatever else you want to show the user. You should also callremoveUpdates()once you’ve got an up-to-date location so that you don’t drain the user’s battery.