getCurrentLocation() of FusedLocationProviderClient returns a success but without the location?

408 Views Asked by At

While it's expected that LastLocation doesn't provide a location for the first time if it's unknown. I didn't expect to see the same issue with GetCurrentLocation.

val mFusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(mContext)
 mFusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, object: CancellationToken() {
                override fun onCanceledRequested(p0: OnTokenCanceledListener) = CancellationTokenSource().token
                override fun isCancellationRequested() = false
            }).addOnCompleteListener { it ->
                if (it.isSuccessful) {
                    val location: Location = it.result
                    // Why can this be null if it was a success?
                }
            }

How can it.isSuccessful be true and at the same time, showing the it.result (location) as null?

1

There are 1 best solutions below

5
CoolMind On

I think, it's a behaviour of Task. When you call addOnCompleteListener, it returns a result, while addOnFailureListener listens to Task fail. In this case getCurrentLocation() tries to access/compute a current location:

This may return a cached location if a recent enough location fix exists, or may compute a fresh location. If unable to retrieve a current location fix, null will be returned.

addOnFailureListener will return an error. Maybe permissions were not granted or GPS provider didn't work, I don't know.