you should probably use the LocationManager
object to get and access Location updates. You can query it for the last known location for a quick update.
The key things is, I ask the location manager to start listening and then from there I can ask for quick updates anytime. I store the updated location information in my ApplicationContext
object (which I call appModel
locally) which is persistent throughout the life of the object.
I use the LocationManager
like this:
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
startListening();
Start listening looks like this:
public void startListening() {
if (gpsLocationListener == null) {
// make new listeners
gpsLocationListener = new CustomLocationListener(LocationManager.GPS_PROVIDER);
// request very rapid updates initially. after first update, we'll put them back down to a much lower frequency
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener);
}
//get a quick update
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//this is the applicationContext object which persists for the life of the applcation
if (networkLocation != null) {
appModel.setLocation(networkLocation);
}
}
You location listener could look like this:
private class CustomLocationListener implements LocationListener {
private String provider = "";
private boolean locationIsEnabled = true;
private boolean locationStatusKnown = true;
public CustomLocationListener(String provider) {
this.provider = provider;
}
@Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
handleLocationChanged(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
startListening();
}
public void onProviderDisabled(String provider) {
}
}
private void handleLocationChanged(Location location) {
if (location == null) {
return;
}
//get this algorithm from: http://developer.android.com/guide/topics/location/obtaining-user-location.html
if (isBetterLocation(location, appModel.getLocation())) {
appModel.setLocation(location);
stopListening();
}
}
Good luck!