getLastKnownLocation() returns null even with best

2019-08-02 09:38发布

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条回答
够拽才男人
2楼-- · 2019-08-02 10:10

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.

查看更多
登录 后发表回答