最近在使用Android自带的LocationManager获取地理位置信息时,遇到在室内测试locationManager.getLastKnownLocation(provider)一直为空,至于权限之类的都在AndroidManifest.xml
中配置了,并且也动态权限申请了,依旧为空很是头疼,最后实在StackOverflow上找到了答案,现在将解决过程记录一下。
第一次尝试通过 Criteria
去获取还是为null:
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度,如果设置为高精度,依然获取不了location。
criteria.setAltitudeRequired(false);//不要求海拔
criteria.setBearingRequired(false);//不要求方位
criteria.setCostAllowed(true);// 允许有花费
criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
provider = locationManager.getBestProvider(criteria, true);
if ("".equals(provider)) {
return "当前设备无定位器";
} else {
Location location = locationManager.getLastKnownLocation(provider);
}
第二次是通过遍历getAllProviders()获取provider还是为null:
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
List<String> allProviders = locationManager.getAllProviders();//获取设备所有的定位器
String provider = "";
if (allProviders.contains(LocationManager.GPS_PROVIDER)) {//优先选用GPS定位
provider = LocationManager.GPS_PROVIDER;
} else if (allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
}else {
provider=LocationManager.PASSIVE_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(provider);
最终解决办法:通过以下方法遍历provider获取,完美解决,附上Stackoverflow的参考地址以及解决后的效果图
private Location getLastKnownLocation(LocationManager locationManager) {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}