我使用以下代码从我的应用程序中的网络提供程序获取当前位置:
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显示的位置。
与Navigator,Maps等谷歌应用程序相同的事情......,
如何做到这一点?其他应用程序如何才能获得确切位置,仅基于网络提供商?
完整代码:
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();
}
}
}
谢谢
答案 0 :(得分:3)
您将获得最后一个已知位置。您应该从LocationManager
请求位置更新。使用LocationManager.getLocationUpdates
。
在onLocationChanged(Location location)
方法的LocationListener
上,您可以查看Location
对象,此位置的准确程度如下:
float accuracy=location.getAccuracy();
然后,如果此Location
对您来说足够准确,您可以停止使用removeUpdates()
从LocationManager
接收位置更新,并使用收到的Location
。如果Location
不够准确,您可以等待更精确的Location
,并在后面停止更新。