事情的起因就是我用系统的GetLastKnownLocation输出结果永远是null。后来看大家说这个方法在室内90%都不管用。
于是查了国内各大网站给出了两个解决办法:
1.while(GetLastKnownLocation(provider) = null){
GetLastKnownLocation = null
}
2.locationManager.setTestProviderEnabled(provider1, false);
然而这两种方法并没能解决我的问题。只是疯狂在while里循环,知道我的App崩溃。。。
最后查询StackOverflow得到解决办法。
用如下办法获取Last Location
LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();
private Location getLastKnownLocation() {
mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
结果很成功。
激动之余记录一下,并分享给大家。
原文链接:https://stackoverflow.com/questions/20438627/getlastknownlocation-returns-null