我使用以下代码从应用程序中的网络提供商获取当前位置:
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();
}
}
}
谢谢
您得到的只是最后的已知位置。您应该向以下位置请求位置更新LocationManager
. Use LocationManager.getLocationUpdates http://developer.android.com/reference/android/location/LocationManager.html.
On your LocationListener http://developer.android.com/reference/android/location/LocationListener.html on the onLocationChanged(Location location)
方法,您可以检查Location http://developer.android.com/reference/android/location/Location.html对象,这个位置有多准确,如下所示:
float accuracy=location.getAccuracy();
那么,如果这Location
对您来说足够准确,您可以停止接收来自LocationManager
using removeUpdates() http://developer.android.com/reference/android/location/LocationManager.html#removeUpdates%28android.location.LocationListener%29,并使用收到的Location
。如果Location
不够准确,可以等更准确的Location
,并停止更新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)