Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLastKnownLocation() returns null [closed]

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

like image 477
XeniaSis Avatar asked Feb 09 '23 22:02

XeniaSis


1 Answers

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.

like image 110
CommonsWare Avatar answered Feb 15 '23 10:02

CommonsWare