如何可靠地获得Glass上的最后位置?

Dav*_*vra 7 google-glass google-gdk

getLastLocation()LocationManager经常返回null的方法来选择最佳提供者是非常棘手的.文件说:

警告:不要使用LocationManager.getBestProvider()方法或常量GPS_PROVIDER或NETWORK_PROVIDER来侦听位置更新.Glass使用一组动态提供程序,仅侦听单个提供程序可能会导致应用程序错过位置更新.

如何获得最佳位置?

Dav*_*vra 8

由于Glass使用动态的提供程序集,因此您需要从所有提供程序获取位置并以最准确的方式选择位置:

 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;
 }
Run Code Online (Sandbox Code Playgroud)