即使使用最佳提供程序,getLastKnownLocation()也会返回null

Arc*_*pgc 1 android location locationmanager

这是我用来获取当前位置的代码:

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
}
Run Code Online (Sandbox Code Playgroud)

几乎每次都有 best = network

但它有时并没有提供这个位置.

mgr.getLastKnownLocation(best) returns null
Run Code Online (Sandbox Code Playgroud)

也:

onResume() {
    mgr.requestLocationUpdates(best, 15000, 10, this);
}
Run Code Online (Sandbox Code Playgroud)

onPause() {
    mgr.removeUpdates(this);
}
Run Code Online (Sandbox Code Playgroud)

这种情况有替代方案吗?

一种选择可能是

List<String> providers = mgr.getAllProviders();
Run Code Online (Sandbox Code Playgroud)

存储所有提供商并逐步减少1.但从未在任何地方看到过此推荐.此外,要求最好的提供者是文档建议的.

Rag*_*ood 7

getLastKnownLocation()如果最近使用过该提供程序,则仅返回提供程序的Location对象.如果它最近没有,Android会假定该提供程序提供的最后一个位置是过时和错误的,并返回null.

在这种情况下,onLocationChanged()在有可用位置之前,必须等待调用LocationListener的方法.