我正在检索用户位置:
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false); // GPS
locationManager.requestLocationUpdates(provider, 400, 1, this);
Location location = locationManager.getLastKnownLocation(provider);
提供商字符串是GPS。 getLastKnownLocation
返回我住的地方的坐标,而不是我现在的位置。距离酒店有35英里。当我开车上班时,手机GPS已开启。然而,当我使用Android Studio在手机上运行我的应用程序时,它会返回我住的地方的纬度和经度,而不是我的位置。为什么会这样?
答案 0 :(得分:1)
为了获得准确的当前位置,您需要使用Fused location provider,这是使用Fused location provider的一个很好的例子。你可以找到here!
答案 1 :(得分:1)
试试此代码
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
locationManager.requestLocationUpdates(provider, 400, 1, this);
Location location = getLastKnownLocation();
private Location getLastKnownLocation() {
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()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}