GPS provider sometimes is battery energy hungry and also needs to retrieve the GPS signal, warm up the hardware and then get the location, this could take some time if there is the first time using it.
What I recommend is to use the new LocationRequest which will select between GPS or NETWORK to get the location if needed.
Firs in onCreate I setup my locationRequest
private fun setupLocationRequest(){
locationCallback = LocationCallback()
locationRequest = LocationRequest.create()
locationRequest.interval = 10000
locationRequest.fastestInterval = 2000
locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
as you can see here PRIORITY_BALANCED_POWER_ACCURACY
will give me a block of distance max for latitude and longitude and also will not just use GPS but it will use NETWORK if needed.
Then, I request first the lastKnowLocation
, if this location is not retrieved , you can request location updates
fusedLocationClient.lastLocation.addOnSuccessListener { lastLocation ->
if(lastLocation != null){
calculateDistanceAndNavigate(lat,lng,lastLocation.latitude,lastLocation.longitude,radio)
}else{
startLocationUpdates()
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations) {
calculateDistanceAndNavigate(lat,lng,location.latitude,location.longitude,radio)
}
}
}
}
}
private fun startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
}
For me this is the most efficient way to get the location, first I dont use just GPS but instead I save battery and also use NETWORK or WIFI if needed, then I request the lastKnownLocation if it is saved (maybe by another app, eg: google maps) and then if that fails I just start requesting location updates (which could take a little bit)