首页 > 解决方案 > 用户位置不打印纬度/经度

问题描述

首先,我想检查用户的位置设置:

fun checkSettings() {
    val builder = LocationSettingsRequest.Builder()

    val client: SettingsClient = LocationServices.getSettingsClient(this)
    val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

    task.addOnSuccessListener { locationSettingsResponse ->
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
    }

    task.addOnFailureListener { exception ->
        if (exception is ResolvableApiException){
             fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
            try {
                exception.startResolutionForResult(this@MainActivity, 500)
            } catch (sendEx: IntentSender.SendIntentException) {
                println("Error")
            }
        }
    }

我在方法中添加了这个功能onCreate。如果一切正常,这个其他函数onCreate应该打印纬度和经度:

locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult?) {
            locationResult ?: return
            for (location in locationResult.locations){
                println(location.latitude)
                println(location.longitude)
            }
        }
    }

但它不起作用。我很抱歉,但我很困惑,我不知道我应该做什么。有任何想法吗?

标签: androidkotlinlocation

解决方案


推荐阅读