问题
This is the Code I use to get the current location:
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
if (best == null) {
//ask user to enable atleast one of the Location Providers
} else {
Location location = mgr.getLastKnownLocation(best);
//But sometimes it returns null
}
Almost everytime best = network
But it's not providing the location sometimes.
mgr.getLastKnownLocation(best) returns null
Also:
onResume() {
mgr.requestLocationUpdates(best, 15000, 10, this);
}
and
onPause() {
mgr.removeUpdates(this);
}
Is there any alternate for such cases?
One option might be
List<String> providers = mgr.getAllProviders();
Store all the providers and go 1 by 1. But never saw this recommended anywhere. Moreover asking for the best provider is what the docs suggest.
回答1:
getLastKnownLocation()
only returns a Location object for a provider if that provider has been used recently. If it has not been recently, Android assumes that whatever was the last location given by that provider is out of date and wrong, and returns null.
In such a case, you will have to wait for your LocationListener's onLocationChanged()
method to be called before you have a usable location.
来源:https://stackoverflow.com/questions/15409754/getlastknownlocation-returns-null-even-with-best-provider