getLastKnownLocation returns null

Aleksander Fimreite picture Aleksander Fimreite · Dec 7, 2013 · Viewed 74.6k times · Source

I've read some questions about this, but I didn't quite find an answer that I needed.

So, the case is that I have my map set up, and I want to grab my current gps location. I have checked that my variables is not NULL but yet my result from:

getLastKnownLocation(provider, false);

Gives me null though, so this is where I need help. I have added permissions for COARSE + FINE location. But I usually have all kinds of network data disabled for my phone, because I'm not very happy about unpredictable dataflow expenses in my phone bill. So I have only WiFi enabled and connected for this test.

Is there anything more I NEED to enable in order for this to be possible? I would think WiFi should be sufficient?

Answer

TharakaNirmana picture TharakaNirmana · Dec 9, 2013

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