【问题标题】:getLastKnownLocation() returns null even with best provider即使使用最佳提供者,getLastKnownLocation() 也会返回 null
【发布时间】: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


【解决方案1】:

getLastKnownLocation() 仅在最近使用过该提供者的情况下才返回该提供者的 Location 对象。如果不是最近,Android 会假定该提供程序提供的最后一个位置是过时且错误的,并返回 null。

在这种情况下,您必须等待 LocationListener 的 onLocationChanged() 方法被调用,然后才能获得可用的位置。

【讨论】:

  • 什么时候会调用onLocationChanged()。因为如果它依赖于设备移动,无论我尝试多少次,它都会返回null,除非用户移动?
  • 只要有一个位置与最后一个已知位置不同,就应该调用它。因此,在这种情况下,由于您为此获得了 null,因此当提供者获得初始修复时,应至少调用一次 onLocationChanged()。这可以从几秒钟到几分钟不等。
  • 好的。 1 最后一个问题。我目前正在测试的设备从未离开过这个城市。这些天来,它给出了正确的当前位置。但是昨天它给出了一个 lat lng 的差异 5。这是一个距离我当前位置 1200 公里的地方。知道是什么原因造成的吗?
  • 你有没有关于getLastKnownLocation() 行为的官方文档/链接? javadoc 非常苗条 - 另见讨论here
  • 如果文档确实描述了这种行为,那就太好了;文档声明它返回的位置可能已过时,如果提供程序被禁用,则返回 null。
猜你喜欢
  • 2023-03-22
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2013-12-24
  • 1970-01-01
相关资源
最近更新 更多