LocationManager.getLastKnownLocation() returns null, and onLocationChanged never gets called

Charlie-Blake picture Charlie-Blake · Aug 24, 2012 · Viewed 6.9k times · Source

This code is used on the onCreate block in my MapActivity

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);

No matter what, loc always returns null. Anyway, when I register for updates on the GPS, the logcat logs my position correctly.

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

So I thought I could implement what I want to do via the onLocationChanged() method. No luck either.

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");
    }

}

What am I doing wrong?

Answer

monish_sc picture monish_sc · Aug 24, 2012

Please check out whether, provider is currently enabled because If the provider is currently disabled, null is returned. http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)