如何可靠地获得Glass的最后位置? [英] How to get last location on Glass reliably?
问题描述
LocationManager
中的方法getLastLocation()
通常返回null,选择最佳提供程序非常棘手.该文档说:
Method getLastLocation()
from LocationManager
often return null and it's quite tricky to select best provider. The documentation says:
警告:请勿使用LocationManager.getBestProvider()方法或常量GPS_PROVIDER或NETWORK_PROVIDER来侦听位置更新. Glass使用一组动态的提供程序,并且仅侦听单个提供程序可能会导致您的应用程序丢失位置更新.
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?
推荐答案
由于Glass使用动态的提供程序集,因此您需要从所有提供程序中获取位置并以最佳的精度选择位置:
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;
}
这篇关于如何可靠地获得Glass的最后位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!