【发布时间】:2013-03-16 02:01:47
【问题描述】:
我在我的应用程序中使用以下代码从网络提供商获取当前位置:
LocationManager mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean network_enabled = mgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(network_enabled){
Location location = mgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
但它给出的位置距离我的实际位置大约 300-700 米。
这是网络提供商所期望的。但问题是:
只启用了这个网络提供商,没有 GPS,我打开了 Foursquare 应用程序,它准确地显示了我当前的位置。现在 当我回到我的应用程序时,它会显示准确的电流 位置或说出 Foursquare 显示的相同位置。
导航器、地图等 Google 应用也会发生同样的情况,
如何做到这一点?其他应用如何仅根据网络提供商获取确切位置?
完整代码:
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
Location location;
public static double myLocationLatitude;
public static double myLocationLongitude;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
location = mgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
dumpLocation(location);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
@Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 10, this);
}
private void dumpLocation(Location l) {
if (l != null){
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
}
谢谢
【问题讨论】:
-
如果您使用的是 android 4.2 与之前的 Android 版本相比,如果您的应用请求 ACCESS_COARSE_LOCATION 权限但未请求 ACCESS_FINE_LOCATION 权限,则用户位置结果可能会不太准确。当您的应用请求粗略位置(而非精细位置)权限时,为了满足用户的隐私期望,系统不会提供比城市街区更准确的用户位置估计。
-
我在
4.1.2上试过。但无论如何我都要求ACCESS_COARSE_LOCATION和ACCESS_FINE_LOCATION的许可。 -
您可以尝试减少更新之间的时间吗?后一个位置发送的位置是否比前一个更准确?
-
是的。我尝试将其设置为 5 秒。结果还是一样。
mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, this);