4

I have read a lot of Q&As on this topic here on SO but I have to say that none of them works.

My problem is that, even though I have GPS enabled, I cannot get a location unless I open Google Maps and get my location and then go back to the app, which is definitely not an option for the users.

I have the following function to get the location.

public Location getCurrentLocation() {
    LocationManager locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location myLocation = locationManager.getLastKnownLocation(provider);

    return myLocation;
}

Is there anything I'm missing on how to solve this? I have also tried this http://developer.android.com/training/location/retrieve-current.html#last-known but still returns null.

Thanks in advance

XeniaSis
  • 2,192
  • 5
  • 24
  • 39
  • possible duplicate of [getlastknownlocation always return null after I re-install the apk file via eclipse](http://stackoverflow.com/questions/15997079/getlastknownlocation-always-return-null-after-i-re-install-the-apk-file-via-ecli) – Dhaval Parmar Jun 05 '15 at 11:05
  • I tried this, didn't work for me – XeniaSis Jun 05 '15 at 11:07

1 Answers1

8

Is there anything I'm missing on how to solve this?

GPS radios are powered down normally, as they are major battery drain. Hence, getLastKnownLocation() can frequently return null or a stale location, because nothing is checking for location fixes. getLastKnownLocation(), therefore, is only useful if you have a casual interest in the location and are happy if there is no location.

If you need to know the location, you will need to use requestLocationUpdates() or similar stuff, to cause Android to power on the GPS radio and actively try to find the location.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    Could you point out an example or a link to one? – XeniaSis Jun 05 '15 at 11:43
  • @XeniaSis: The documentation has https://developer.android.com/training/location/receive-location-updates.html for the fused location provider from Play Services. There is also https://github.com/commonsguy/cw-omnibus/tree/master/Location/Periodic and plenty of other examples floating around, findable by a search engine, for using `LocationManager` and its `requestLocationUpdates()`. – CommonsWare Jun 05 '15 at 11:53
  • thanks, I'll go through them – XeniaSis Jun 05 '15 at 12:14