getLastKnownLocation() returns null even with best provider

喜欢而已 提交于 2020-01-05 07:49:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!