Method getLastLocation()
from LocationManager
often return null and it's quite tricky to select best provider. The documentation says:
Warning: Do not use the LocationManager.getBestProvider() method or the constants GPS_PROVIDER or NETWORK_PROVIDER to listen for location updates. Glass uses a dynamic set of providers and listening only to a single provider may cause your application to miss location updates.
How to get best last location?
Because Glass uses dynamic set of providers, you need to get location from all of them and select the location with best accuracy:
public static Location getLastLocation(Context context) {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
List<String> providers = manager.getProviders(criteria, true);
List<Location> locations = new ArrayList<Location>();
for (String provider : providers) {
Location location = manager.getLastKnownLocation(provider);
if (location != null && location.getAccuracy()!=0.0) {
locations.add(location);
}
}
Collections.sort(locations, new Comparator<Location>() {
@Override
public int compare(Location location, Location location2) {
return (int) (location.getAccuracy() - location2.getAccuracy());
}
});
if (locations.size() > 0) {
return locations.get(0);
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With