【问题标题】:Kotlin: How to get current location?Kotlin:如何获取当前位置?
【发布时间】:2021-01-20 15:02:25
【问题描述】:

我正在尝试获取实际位置。我阅读并尝试了几十个例子。但一切都以错误告终。

示例: val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager

以这个错误结束: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Context?

或者我试过this。但是ActivityCompatcontent在Android studio中是红色的。

我尝试了xx版本,但总是出现一些错误。

我正在创建 GPS 跟踪器。我从简单的位置检测开始。

你知道一些 Android studio 4.1.2 的例子吗?

【问题讨论】:

    标签: android kotlin gps


    【解决方案1】:
    Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Context?
    

    这意味着变量 context 属于 Kotlin nullable type。在 Kotlin 中,与 Java 不同,您需要指定变量是否可以为 null。访问此类变量是通过语法 variable?.method() 完成的,表示您了解该调用可能评估为 null。

    所以在你的例子中,它看起来像:

    val locationManager = context?.getSystemService(LOCATION_SERVICE) as? LocationManager
    

    由于locationManager 被分配了一个可以为空的类型,它现在也可以为空了。您可以通过执行以下操作来缓解这种情况:

    val locationManager = (context?.getSystemService(LOCATION_SERVICE) as? LocationManager) ?: error("Could not get LocationManager")
    

    【讨论】:

    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多