【问题标题】:getCurrentLocation() method in Kotlin?Kotlin 中的 getCurrentLocation() 方法?
【发布时间】:2022-06-15 14:00:11
【问题描述】:

当我尝试实现一个获取设备位置的简单示例时,我发现一个“看似官方”的文档: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 方法的人。

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    在 kotlin 中,getX 形式的任何方法都可以写成 x,这称为“属性访问语法”。没有单独的 kotlin 版本。 fusedLocationClient.lastLocationfusedLocationClient.getLastLocation() 完全一样。如果需要,您甚至可以在 kotlin 中编写最后一种形式。

    但是,这仅适用于没有参数的“get”方法。问题是,getCurrentLocation 确实有参数,所以在这种情况下属性访问语法是不可能的。如您所见here 这是此方法的签名:

    public Task<Location> getCurrentLocation (int priority, CancellationToken token)
    

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

    fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)
    

    编辑:

    显然null 作为参数是不允许的。根据https://stackoverflow.com/a/72159436/1514861,这是一种可能性:

    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
                }
    
            }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多