问题描述
我正在使用网络提供商来获取用户的最后一个已知位置。当我测试它时,它在我的一部手机上运行良好,但纬度和经度在另一部手机上返回空值。是否有替代位置管理器以获得更一致的结果。或者我的代码中还有其他错误
这是我的权限检查代码:
if (ContextCompat.checkSelfPermission(
applicationContext,Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Please Grant Location Permissions")
.setPositiveButton("Ok",null)
.show()
ActivityCompat.requestPermissions(
this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),101
)
}
还有我的位置请求代码
longitude =
locationManager.getLastKNownLocation(LocationManager.NETWORK_PROVIDER)?.longitude
latitude =
locationManager.getLastKNownLocation(LocationManager.NETWORK_PROVIDER)?.latitude
val geocoder = Geocoder(this)
if (latitude != null && longitude != null) {
val addresses: List<Address> = geocoder.getFromLocation(latitude,longitude,1)
val cityName = addresses[0].subAdminArea
}
解决方法
正如文件所说
从给定的提供者获取最后一个已知位置,如果没有最后一个已知位置,则为 null。在某些情况下,返回的位置可能很旧,因此应始终检查位置的年龄。 这永远不会激活传感器来计算新位置,并且只会返回缓存的位置。 另请参阅 getCurrentLocation(String,CancellationSignal,Executor,Consumer) ,它将始终尝试返回当前位置,但与此方法相比,在尝试过程中可能会使用额外的功率。 参数: provider – 由 getAllProviders() 列出的提供者 返回: 给定提供者的最后一个已知位置,如果不可用则为 null 抛出: SecurityException - 如果没有合适的权限存在 IllegalArgumentException – 如果提供者为空或不存在
因此,如果最后一个位置返回 null,您必须请求新的或自定义处理程序