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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With