Skip to content

Instantly share code, notes, and snippets.

@luixal
Created May 6, 2013 02:55
Show Gist options
  • Save luixal/5523121 to your computer and use it in GitHub Desktop.
Save luixal/5523121 to your computer and use it in GitHub Desktop.
Get last known location from all providers without using any criteria but time.
public Location getLastKnownLocation() {
// variable for keeping most up to date location:
Location lastLocation = null;
// getting location manager:
LocationManager locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
// getting list of providers:
List<String> providers = locationManager.getAllProviders();
// getting most up to date location from any enabled provider:
if (providers != null && !providers.isEmpty()) {
for (String provider:providers) {
if (locationManager.isProviderEnabled(provider)) {
Location auxLocation = locationManager.getLastKnownLocation(provider);
Log.d("TAG", "LastKnownLocation from " + provider + " @ " + new Date(auxLocation.getTime()) + " >> " + auxLocation.getLatitude() + "," + auxLocation.getLongitude());
if (lastLocation == null) {
lastLocation = auxLocation;
} else {
if (auxLocation.getTime() > lastLocation.getTime()) lastLocation = auxLocation;
}
}
}
}
// returning location:
return lastLocation;
}
// In logcat we should see something like this:
// D/TAG( 4002): LastKnownLocation from passive @ Mon May 06 04:48:16 CEST 2013 >> 40.4942683,-3.6603943
// D/TAG( 4002): LastKnownLocation from gps @ Sun May 05 08:59:22 CEST 2013 >> 40.49400951247662,-3.6610011477023363
// D/TAG( 4002): LastKnownLocation from network @ Mon May 06 04:48:16 CEST 2013 >> 40.4942683,-3.6603943
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment