Location总是返回null



我正在实现一个函数来找到我的纬度和经度,但它一直给出一个空值。我宣布了android许可。ACCESS_FINE_LOCATION android.permission。ACCESS_BACKGROUND_LOCATION android.permission。ACCESS_COARSE_LOCATION和android.permission.INTERNET.

我授予了所有权限,它显示了一个"授予"吐司,但为什么我的位置总是空的?

MainActivity

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var fusedLocationProviderClient : FusedLocationProviderClient
companion object {
private const val PERMISSION_REQUEST_ACCESS_LOCATION = 100
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
getCurrentLocation()
}
private fun getCurrentLocation() {
if( checkPermissions() )
{
if(isLocationEnabled())
{
if (ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
){
requestPermission()
return
}
fusedLocationProviderClient.lastLocation.addOnCompleteListener(this) { task ->
val location : Location? = task.result
if(location == null)
{
Toast.makeText(this, "Null Received", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(this, "Get Success", Toast.LENGTH_SHORT).show()
binding.txtLat.text = ""+location.latitude
binding.txtLong.text = ""+location.longitude
}
}
}
else
{
Toast.makeText(this, "Turn on location", Toast.LENGTH_SHORT).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
}
else
{
//request permission here
requestPermission()
}
}
private fun isLocationEnabled() : Boolean {
val locationManager : LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
private fun requestPermission() {
ActivityCompat.requestPermissions(
this, arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_ACCESS_LOCATION
)
}
private fun checkPermissions() : Boolean
{
if(ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
==PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
return true
}
return false
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode ==  PERMISSION_REQUEST_ACCESS_LOCATION){
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(applicationContext, "Granted", Toast.LENGTH_SHORT).show()
getCurrentLocation()
}
else {
Toast.makeText(applicationContext, "Denied", Toast.LENGTH_SHORT).show()
}
}
}
}

As Google:

getLastLocation()方法返回一个Task,您可以使用该Task来获取具有地理位置的经纬度坐标的Location对象。location对象可以为null在以下情况下:

  • 在设备设置中关闭位置。结果可能是空的,即使最后一个位置是以前检索到的,因为禁用位置也会清除缓存。

  • 设备从未记录其位置,这可能是新设备或设备已恢复到出厂设置的情况。

  • 设备上的Google Play服务已经重新启动,并且在服务重新启动后没有活动的Fused Location Provider客户端请求位置

解决方案:

1获取最后知道的位置:

private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy())       {
Log.d("last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}

2接收位置更新:为了避免这种情况,您可以创建一个新客户端并自己请求位置更新。有关详细信息,请参阅接收位置更新链接

在这里我分享了我是如何解决错误的任何人有相同的问题,我得到了。

所以原因是没有缓存的位置,它不能访问我的最后一个位置。我通过添加这个来解决这个问题。

  1. if(location == null)

    中添加以下内容fusedLocationProviderClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() )

然后,我收到一个错误初始化locationCallback。所以我加了这个。2)在onCreate

中添加以下内容
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
locationResult ?: return
for (location in locationResult.locations){            
}
}
}

最新更新