从SDK上的'getLastKnownLocation'获取null

时间:2009-12-16 18:12:29

标签: android

我遇到了与Location API相关的问题。

我尝试了以下代码:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);

loc总是null,当getLastKnownLocation()被调用时。

有什么问题?

6 个答案:

答案 0 :(得分:6)

AndroidManifest.xml文件中的权限外,您是否注册了位置监听器?

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener); 

然后有一个方法,在本例中为locationListener,以完成您的任务

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

答案 1 :(得分:3)

如果您在模拟器中运行代码,那么获取GPS位置的任何调用都将返回null,直到您明确更新位置(通过EclipseADB)。

答案 2 :(得分:2)

我和你有同样的问题,我总是收到一个null的Location对象,但最后它以一种简单的方式解决了。您必须拥有有效的GPS位置,因此,如果未启用GPS并且您没有足够的信号,则“位置”对象将始终为空。

答案 3 :(得分:1)

您是否在AndroidManifest.xml中设置了权限?您需要这些权限才能通过应用程序访问用户的位置:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

答案 4 :(得分:0)

您可以使用以下内容:

LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Location loc = lm.getLastKnownLocation(bestProvider);

last_lat = loc.getLatitude();
last_lng = loc.getLongitude();

答案 5 :(得分:0)

你需要像这样的LocationManager实例:

初审:

   LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

错:

Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);

正确:

Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);