Reputation: 135
I run my foreground service every 3 minutes. Therefore my goal is: Run a foreground service, get the current user location and then stop the foreground service. So now I use this:
locationCallback = object : LocationCallback(){
override fun onLocationAvailability(locationAvailability: LocationAvailability?) {
super.onLocationAvailability(locationAvailability)
if(locationAvailability!!.isLocationAvailable){
fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
if (location != null) {
// do my action with this location and finish the foreground service
}
}
}else{
prepareFinishService() // finish service
}
}
}
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback, Looper.getMainLooper())
And my locationRequest:
fun createLocationRequest(): LocationRequest {
val locationRequest = LocationRequest.create()
locationRequest.interval = 10000L * 10
locationRequest.fastestInterval = 50000L
locationRequest.smallestDisplacement = 10f
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
return locationRequest
}
But in this solution I get not fresh location. For example user change location but onLocationAvailability
retrun previous location. After some time for example after 15 minutes when my service run it return a updated location.
I know that I can add also this callback :
override fun onLocationResult(locationResult: LocationResult?) {
// my action with location
}
But as per documentation : onLocationResult
"Even when isLocationAvailable() returns true the onLocationResult(LocationResult) may not always be called regularly, however the device location is known and both the most recently delivered location and getLastLocation(GoogleApiClient) will be reasonably up to date given the hints specified by the active LocationRequests."
It is possible that this function will not be called and my service will run all the time until the next start. I do not want this situation. Is there any solution to always access the current service and then stop the service?
Upvotes: 0
Views: 984
Reputation: 2962
For example user change location but onLocationAvailability retrun previous location.
This is what getLastLocation
does. It returns the last known location, it doesn't mean the newest location. According to the documentation :
It is particularly well suited for applications that do not require an accurate location [...]
That said, for a decent accuracy, you should use requestLocationUpdates
.
But don't start/stop you service manually. If you want regular updates on the user location, just set the right parameters.
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(1000*60*3); // max: 3 min
locationRequest.setFastestInterval(1000*60*1); // min: 1 min
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Upvotes: 0