LocationManager.getLastKnownLocation()返回null,并且永远不会调用onLocationChanged

时间:2012-08-24 07:20:37

标签: android android-mapview locationmanager android-location

此代码用于MapActivity中的onCreate块

lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
        {
            Toast.makeText(this,
                    "Por favor, habilita el GPS antes de usar esta opción",
                    Toast.LENGTH_SHORT).show();
            finish();
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        doYourMapMagicBaby(loc);

无论如何,loc总是返回null。无论如何,当我在GPS上注册更新时,logcat会正确记录我的位置。

08-24 09:21:18.479: D/libloc(260): Latitude:  40.4399979 (intermediate)
08-24 09:21:57.500: D/libloc(260): Longitude: -3.6700022

所以我想我可以通过onLocationChanged()方法实现我想做的事情。也没有运气。

public void onLocationChanged(Location location)
{
    if (location != null)
    {
        System.out.println("La localizacion es: (lon: "
                + location.getLongitude() + ", lat: "
                + location.getLatitude() + ")");
        doYourMapMagicBaby(location);
    }
    else
    {
        System.out.println("La location es nula");
    }

}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

请检查提供程序当前是否已启用,因为如果当前禁用了提供程序,则返回null。 http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String