How to get the device's last location

2

I would like to know if there is any way to get the last location of GPS , before I run the option to execute obtaining the current position.

public class Localization{

 private GetGPSResponse delegate = null;

 public void setDelegate(GetGPSResponse delegate){
    this.delegate = delegate;
 }


 //Método que faz a leitura de fato dos valores recebidos do GPS
 public void startGPS(Object local, final Context context){
    final LocationManager lManager = (LocationManager) local ;
    LocationListener lListener = new LocationListener() {
        public void onLocationChanged(Location locat) {
            if( locat != null ) {
                delegate.getGPSResponse(locat);
                lManager.removeUpdates(this);
            }
        }
        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
        @Override
        public void onProviderEnabled(String arg0) {}
        @Override
        public void onProviderDisabled(String arg0) {}
    };
    lManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, lListener, null);
 }

 interface GetGPSResponse{
    void getGPSResponse(Location location);
 }
}
    
asked by anonymous 21.03.2015 / 14:49

1 answer

2

The LocationManager object has the getLastKnownLocation " that you can use for this case, and if it succeeds, you can also get the date of the last location, so you can guarantee that a very old location was not obtained. This is what I usually do.

More or less like this:

boolean isSignificantlyNewer = false;

Location lastKnownLocation = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (lastKnownLocation != null) {
    Date currentDate = new Date();
    long timeDelta = currentDate.getTime() - lastKnownLocation.getTime();
    isSignificantlyNewer = timeDelta < 120000;
}

if (isSignificantlyNewer) {
    // A última localização foi obtida a menos de 2 minutos
} else {
    // Não possui última localização ou ela tem mais de 2 minutos
    lManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, lListener, null);
}
    
21.03.2015 / 15:20