Kotlin:如何获得当前位置?



我试图获得实际位置。我阅读并尝试了几十个例子。但都以错误结束

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

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

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

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

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

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

Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Context?

这意味着变量context是Kotlin可空类型。在Kotlin中,与Java不同,您需要指定变量是否可以为空。访问这样的变量是通过语法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")

最新更新