Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last location on Glass reliably?

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?

like image 993
David Vávra Avatar asked Jan 26 '14 14:01

David Vávra


1 Answers

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;
 }
like image 173
David Vávra Avatar answered Sep 29 '22 16:09

David Vávra