【问题标题】:Android Studio Emulator Returning Null Location DataAndroid Studio 模拟器返回空位置数据
【发布时间】:2021-02-15 05:19:35
【问题描述】:

我正在学习 Kotlin,我正在尝试制作一个简单的应用来显示用户的经度/纬度。一切似乎都应该正常工作,但位置数据不断抛出“null else{}”的情况。下面是我的代码的样子。

class MainActivity : AppCompatActivity() {

val RequestPermissionCode = 1
var mLocation: Location? = null
private lateinit var fusedLocationClient: FusedLocationProviderClient

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    getLastLocation()
}

fun getLastLocation(){
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermission()
    }
    else{
        fusedLocationClient.lastLocation
                .addOnSuccessListener {location: Location? ->
                    mLocation = location
                    if(location != null){
                        latitude.text = location.latitude.toString()
                        longitude.text = location.longitude.toString()
                    }
                    else{
                        latitude.text = "LOCATION_DENIED"
                        longitude.text = "LOCATION_DENIED"
                    }
                }
    }
}

private fun requestPermission(){
    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), RequestPermissionCode)
    this.recreate()
}

}

任何帮助将不胜感激!我要开始拔头发了,在谷歌上找不到答案):

【问题讨论】:

    标签: android android-studio kotlin gps


    【解决方案1】:

    我注意到模拟器有位置数据问题,加上 lastLocation 没有发出位置请求,所以很有可能没有位置数据。您需要的是 requestLocationUpdate 方法,以便它可以检索用户的活动位置。此外,您在最后一个位置的物理设备上会有更好的运气。

    【讨论】:

    • 您好!非常感谢您,您的评论绝对让我朝着正确的方向前进!我刚刚验证了您的假设是正确的,因为当我启动 Google 地图应用程序以更新我的位置,然后重新打开我自己的应用程序时,位置就在那里。所以现在我只需要弄清楚如何实现位置更新方法
    • 我之前在这里回答了一个关于位置更新的问题,看看stackoverflow.com/questions/66164852/…
    • 谢谢!刚刚想通了!这行代码修复了它:fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)
    猜你喜欢
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 2018-05-11
    • 2017-08-01
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多