How to get the last device location

Asked

Viewed 514 times

2

I wonder if there’s any way to get the last location of GPS, before I run the option to perform 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);
 }
}
  • You could save the variable Location locat for a variable in the class. Type: public class Localization{ private Localtion lastLocat.

1 answer

2

The object Locationmanager has the method getLastKnownLocation which you can use for this case, and if successful, it is also possible to get what was the date of this last location, so you guarantee that it was not obtained a very old location. That’s what I usually do.

Sort of 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.