【问题标题】:Get current location as fast as possible with Google Play Services?使用 Google Play 服务尽快获取当前位置?
【发布时间】:2017-08-03 18:10:14
【问题描述】:

我正在开发一个需要获取当前位置的 android 应用程序。我已成功编写代码,并且正在使用 Google Play 服务 获取当前位置。

问题是有时它会在很长一段时间后给我位置。我注意到它仅供第一次使用该应用程序。

有什么方法可以避免这个问题并快速获取当前位置?它与我的代码中的 google play 服务版本有关吗? (我没有使用最后一个,实际上我使用的是 9.8.0 版本。)

【问题讨论】:

  • 您现在使用哪种方法获取位置?
  • 避免使用getLastLocation,它会收集保存在任何应用程序缓存中的位置。
  • 我正在使用 requestLocationUpdates
  • 我在第一个活动中使用 getLastLocation,我只是在其中显示位置,在地图活动中我使用 requestLocationUpdates 但我在这两个活动中都遇到了同样的问题。

标签: android location google-play-services


【解决方案1】:

正如@tahsinRupam 所说,避免使用getLastLocation,因为它很容易返回null。它也不会请求新的位置,所以即使你得到一个位置,它也可能很旧,并且不能反映当前位置。您可能想查看此线程中的示例代码:get the current location fast and once in android

public void foo(Context context) {
  // when you need location
  // if inside activity context = this;

  SingleShotLocationProvider.requestSingleUpdate(context, 
   new SingleShotLocationProvider.LocationCallback() {
     @Override public void onNewLocationAvailable(GPSCoordinates location) {
       Log.d("Location", "my location is " + location.toString());
     }
   });
}

您可能想要验证 lat/long 是实际值,而不是 0 或其他值。如果我没记错的话,这不应该抛出 NPE,但您可能需要验证这一点。

这是另一个可能有帮助的 SO 帖子:

【讨论】:

  • 谢谢,但此解决方案使用的是 locationManager,我想将我的项目保留在 Google Play 服务中
猜你喜欢
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
相关资源
最近更新 更多