Android Studio Emulator返回空位置数据
我正在学习Kotlin,我正在尝试制作一个简单的应用程序来显示用户long/lat。一切看起来都应该正常工作,但是位置数据不断抛出“null else{}”的情况。下面是我的代码的样子Android Studio Emulator返回空位置数据,android,android-studio,kotlin,gps,Android,Android Studio,Kotlin,Gps,我正在学习Kotlin,我正在尝试制作一个简单的应用程序来显示用户long/lat。一切看起来都应该正常工作,但是位置数据不断抛出“null else{}”的情况。下面是我的代码的样子 class MainActivity : AppCompatActivity() { val RequestPermissionCode = 1 var mLocation: Location? = null private lateinit var fusedLocationClient: FusedLoca
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()
}
}
任何帮助都将不胜感激!我马上就要发疯了,在谷歌上找不到答案):我注意到模拟器的位置数据有问题,加上lastLocation没有发出位置请求,所以很有可能没有位置数据。您需要的是requestLocationUpdate方法,以便它能够检索用户的活动位置。此外,对于最后一个位置,您在物理设备上的运气会更好。您好!非常感谢你,你的评论肯定给我指明了正确的方向!我刚刚验证了你的假设是正确的,因为当我启动谷歌地图应用程序来更新我的位置,然后重新打开我自己的应用程序时,位置就在那里。所以现在我只需要弄清楚如何实现位置更新方法我在这里回答了一个关于位置更新的问题,看一下谢谢!就这么想出来了!这行代码修复了它:fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY\u高精度,null)