How to get once my last location in android?

Viewed 685

I want to know how can I get my last known location (GPS or network provided). I'm asking this because I know how to get my location but it's going to be updated periodically and I just want it once and no any more.

Here's my actual code:

@Override
public void onLocationChanged(Location location) {
    Toast.makeText(getContext(),"Cambio posicion "+location.getProvider(),Toast.LENGTH_SHORT).show();

     this.marca.title("Mi ubicacion");
     this.marca.position(new LatLng(location.getLatitude(),location.getLongitude()));

     mMap.addMarker(this.marca);

     this.camara = CameraPosition.builder()
             .bearing(0)
             .zoom(15)
             .target(new LatLng(location.getLatitude(),location.getLongitude()))
             .tilt(30)
             .build();

     mMap.animateCamera(CameraUpdateFactory.newCameraPosition(this.camara));


}

I'm using LocationManager. Thanks for your help.

2 Answers

If you are using LocationManager and you just want to get last location once. You can remove listen location update after first onLocationChanged like

@Override
public void onLocationChanged(Location location) {

   mLocationManager.removeUpdates(mListener);
}

Another solution I think it may help is. You can use GoogleLocationService instead of LocationManager. Then you can use this method for get last known location

mFusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location
            }
        });

If you are using Fused Location Provider, you can stop listening for location changed event after the first one like this:

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", new Gson().toJson(location));
    stopLocationUpdates();
}

private void stopLocationUpdates() {
    mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
Related