getLastKnownLocation returns null

Use this method to get the last known location:

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

Leave a Comment