我试图使用一个应用程序访问我的Android手机的位置信息,但我似乎无法获得当前的位置。我的代码如下:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())
val location_button = view.findViewById<ImageButton>(R.id.get_location)
location_button.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED || ContextCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
val permission = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION)
requestPermissions(permission, LOC_PERMISSION_CODE)
}
else {
//permission already granted
fusedLocationClient.lastLocation
.addOnSuccessListener { location ->
// Got last known location. In some rare situations this can be null.
val latitude = location?.latitude
val longitude = location?.longitude
println(latitude)
println(longitude)
}
.addOnFailureListener {
Toast.makeText(requireActivity(), "Failed on getting current location",
Toast.LENGTH_SHORT).show()
}
}
}
else {
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location. In some rare situations this can be null.
println(location)
}
}在第一次运行时,我成功地被提示授予位置访问权,并且我这样做了。然后它调用lastLocation,它总是等于null。如果我再次运行该应用程序,我将被发送到第一个其他块,在那里我打印出纬度和经度,但是即使我成功地授予了位置访问权,并且调用了最后一个位置,它们都总是打印null。
我开始想,如果一个位置从未被保存过,并且我看到FusedLocationProviderClient类中有一个名为"getCurrentLocation()“的函数,那么最后一个位置可能就不能工作了,但是我不知道如何调用它。我是不是遗漏了什么?
发布于 2022-04-28 05:00:31
正如Gabe建议的那样,如果您不希望自己的位置为空或每次都需要一个新的位置,则必须调用新的位置。
您可以使用getCurrentLocation()方法来完成它,该方法具有优先级和取消令牌。
val priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
val cancellationTokenSource = CancellationTokenSource()
fusedLocationClient.getCurrentLocation(priority, cancellationTokenSource.token)
.addOnSuccessListener { location ->
Log.d("Location", "location is found: $location")
}
.addOnFailureListener { exception ->
Log.d("Location", "Oops location failed with exception: $exception")
}您可以根据您的要求更改优先级,到目前为止,我已经使用了PRIORITY_BALANCED_POWER_ACCURACY,因为它将使用wifi和GPS搜索位置以查找位置,如果您需要更高的精度,可以使用PRIORITY_HIGH_ACCURACY。
我们提供取消令牌,就好像在将来我们不需要位置,例如活动已被用户关闭,所以我们将使用cancellationTokenSoure.cancel()取消请求
发布于 2022-04-28 04:43:45
返回null的LastKnownLocation是标准的。如果位置子系统还没有打开,它就不知道位置是什么,所以返回null。如果要确保不获得null,请请求更新。
只有当您真正知道自己在做什么时,LastKnonLocation才应该被用作一个温和的优化。否则,别叫它。
https://stackoverflow.com/questions/72038038
复制相似问题