Reputation: 123
To get the location i'm doing this:
if (isGPSEnabled) {
if (locatTeste == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
locatTeste = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
but sometimes it gives me an out-of-date location... How can i get the up-to-date location?
Upvotes: 0
Views: 370
Reputation: 3620
What you are doing at requestLocationUpdate() is asking the system to start the GPS and give you back the location, but keep in mind that this call is asynchronic, meaning you will not get the location at the next line but only when it will be ready. That is the reason you sometimes might get not up to date locations (you might not even get location at all). You need to choose what method you want to use, the first one - requestLocationUpdate() will register the class you are using to location updates and will get the location in asyncrhonic time when it's ready. The second method - getLastKnownLocation() will return the last location the system has. that's do work in synchronic way but some times might not be updated. What I would do is first try the second method, check the quality of the location, if it's not up to date use the first method to receive one.
something like that:
if (isGPSEnabled && locationManager != null) {
Location l = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (checkIfLocationIsUpdated(l)){
useLocation(l);
}
else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
@override
public void onLocationChanged(Location l){
useLocation(l);
}
EDIT:
private boolean checkIfLocationIsUpdated(Location l){
long maxInterval = 60*1000; //1 minute
float maxAccuracy = 30; //30 meter.
if (System.currentTimeMillis - l.getTime() < maxInterval && l.getAccuracy < maxAccuracy){
return true;
}
else{
return false;
}
}
Upvotes: 1
Reputation: 886
This is expected.
You are using the function getLastKnownLocation(...) and the application is returning what it has in memory. As per the documentation this could be out of date.
Instead use requestLocationUpdates(...) and pass in the parameters you what on how frequently or under what circumstances you want your Location to update.
Read about Androids Location Manager completely to understand the functions available to you.
Upvotes: 0