【发布时间】:2013-03-14 12:49:03
【问题描述】:
这是我用来获取当前位置的代码:
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
}
几乎每次都best = network
但有时它不提供位置。
mgr.getLastKnownLocation(best) returns null
还有:
onResume() {
mgr.requestLocationUpdates(best, 15000, 10, this);
}
和
onPause() {
mgr.removeUpdates(this);
}
这种情况有替代方案吗?
一个选项可能是
List<String> providers = mgr.getAllProviders();
存储所有提供程序并逐个进行。但从未在任何地方看到此推荐。此外,文档建议是要求最好的提供者。
【问题讨论】:
-
“但它没有提供位置”——如果最近没有尝试使用该提供程序,它将没有位置可以给你。您不妨阅读文档:developer.android.com/guide/topics/location/strategies.html
-
if nothing has tried using that provider recently--第一次使用提供者的方式。不使用getLastKnownLocation(provider)? -
引用我链接到的文档:“在Android中获取用户位置通过回调的方式工作。您表示您希望通过调用从LocationManager(“位置管理器”)接收位置更新requestLocationUpdates(),将 LocationListener 传递给它。”
-
是的,我正在使用
LocationListener。上面的类implements LocationListener和需要的回调都实现了。
标签: android location locationmanager