为什么LocationManager没有最后一个已知位置?

时间:2011-05-29 06:42:07

标签: android google-maps location

我希望用户的位置以及用户在他自己的

之后导航一次
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
if (location != null) {
   System.out.println(location.toString());
   lat=location.getLatitude();
   lng=location.getLongitude();
}     
p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

但是由于移动设备的互联网连接速度慢,我无法获得用户的位置?

2 个答案:

答案 0 :(得分:0)

如果gps LocationProvider已在某处存储了某个位置,则getLastKnownLocation方法将仅返回一个位置。如果用户尚未在其设备上使用gps足够长的时间来获得有效的GPS修复,则该方法将返回null。

即使您检索位置检查位置的时间,也不能保证位置不是很老。

答案 1 :(得分:0)

仅仅获取locationManager并调用getLastKnownLocation()是不够的 因为在有更新之前不会有“最后知道的位置” 您缺少LocationManager类提供的请求:

public void requestLocationUpdates(java.lang.String provider, 
                                   long minTime,
                                   float minDistance, 
                                   android.location.LocationListener listener) 

如果您的活动像我的那样实现了LocationListener,您可以将“this”作为LocationListener传递给源自该类方法的调用。否则,还有其他一些重载采用Activity或Looper类。

locationManager.requestLocationUpdates(provider, minTime, minDistance, this);

为了确保设备获取位置,请求更新 - 但您也可以 想要保护失败找不到提供者或getLastKnownLocation返回null。

locationManager.requestLocationUpdates(provider, 1, 0, this);
mostRecentLocation = locationManager.getLastKnownLocation(provider);
if(mostRecentLocation == null)
// lower your expectations, or send user message with Toast or something similar 

告诉用户打开他们的位置共享或其他提供商服务。