Kotlin 中的 getCurrentLocation() 方法?

Use*_*829 4 android kotlin

当我尝试实现一个获取设备位置的简单示例时,我发现一个“看似官方”的文档:https ://developer.android.com/training/location/retrieve-current#BestEstimate

该文档声称FusedLocationProviderClient提供了以下两种方法:getLastLocation()和getCurrentLocation()。但正如示例中所见 - https://developer.android.com/training/location/retrieve-current#last-known - 两者都getLast/CurrentLocation()存在于 Java 中。相应的 Kotlin 示例说fusedLocationClient.getLastLocation()“与...相同” fusedLocationClient.lastLocation,而且确实效果很好。

我天真地认为应该有相应的“ currentLocation”,例如,fusedLocationClient.currentLocation。

我想知道没有这样的,或者我是唯一一个未能找到相应的 Kotlin 方法的人。

Ivo*_*ers 6

在 kotlin 中,任何形式的方法getX都可以写成x,这称为“属性访问语法”。没有单独的 kotlin 版本。fusedLocationClient.lastLocation真的是一模一样fusedLocationClient.getLastLocation()。如果您愿意,您甚至可以用 kotlin 编写最后一个表单。

然而,这只适用于没有参数的“get”方法。问题是,getCurrentLocation确实有参数,因此在这种情况下属性访问语法是不可能的。正如您在这里看到的,这是该方法的签名:

public Task<Location> getCurrentLocation (int priority, CancellationToken token)
Run Code Online (Sandbox Code Playgroud)

所以你应该这样使用它。例如

fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)
Run Code Online (Sandbox Code Playgroud)

编辑:

显然null作为参数是不允许的。根据/sf/answers/5051160551/这是一种可能性:

fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, object : CancellationToken() {
            override fun onCanceledRequested(p0: OnTokenCanceledListener) = CancellationTokenSource().token

            override fun isCancellationRequested() = false
        })
        .addOnSuccessListener { location: Location? ->
            if (location == null)
                Toast.makeText(this, "Cannot get location.", Toast.LENGTH_SHORT).show()
            else {
                val lat = location.latitude
                val lon = location.longitude
            }

        }
Run Code Online (Sandbox Code Playgroud)

  • null 不是此函数的有效参数,您可以更新解决方法吗? (3认同)