【发布时间】:2021-12-09 23:02:51
【问题描述】:
我正在开发一个需要每 2-3 秒访问一次用户位置的 Android 应用程序(使用 Kotlin)。在过去的几天里,我一直在研究(和测试)解决方案,但我似乎只找到了 Java 中的示例(不容易翻译成 Kotlin)。我也无法从Android's tutorials 中理解它。
我已经做了什么:
- 请求权限(前台和后台 GPS 位置访问)
- 在尝试使用之前确保它们已被接受
- 实现了
onLocationChanged()方法 - 访问了最后一个位置(并使用它)
我想更新位置,以便通过访问最后一个位置,我可以使用 Android 知道的最新位置。
这是我尝试过的,我认为可能更接近实际解决方案(但这绝对是错误的):
val locationListener: LocationListener = this
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener
)
这样做的正确方法是什么?谢谢。
【问题讨论】:
-
“我正在开发一个 Android 应用程序(使用 Kotlin),它需要每 2-3 秒访问一次用户的位置”——无法保证您可以获得位置,更不用说更新频繁地。 “我也无法从 Android 的教程中理解它”——您可能想就您不理解的内容提出问题。 “这是我尝试过的东西,我认为它可能更接近实际的解决方案(但这绝对是错误的)”——可以想象它是正确的,但我们不知道你的结果是什么。
-
FWIW,this sample project 显示在后台获取位置 - 它在 this book 中进行了介绍。 Here is another sample project,用于使用活动和前台服务——this book 涵盖了这一点。
-
@CommonsWare 我在我的问题中显示的代码的结果是 Android Studio 给我一个错误说
None of the following functions can be called with the argument supplied。 this 写在实现 LocationListener(和其他)的活动中。可能是什么原因造成的? -
LocationListener的import是指android.location.LocationListener,还是指其他名为LocationListener的东西?您需要传递android.location.LocationListener作为第四个参数。 -
@CommonsWare 非常感谢!正如你所建议的,我不小心导入了
com.google.android.gms.location.LocationListener,而不是android.location.LocationListener。我的代码现在可以完美运行了。
标签: android kotlin geolocation gps