How can I stop (stop) a location event on android?

0

Good evening thank you very much for answering, I would like to know how I do so that only once that event happens ok I mean the AddOnSuccessListener event ok here I put the code.

   mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onSuccess(Location location) {
                    //Sabiendo que obtuvimos location, lo usamos
                    if (location != null) {
                        Toast.makeText(getApplicationContext(),"Latitud: " +location.getLatitude() + "Longitud: " + location.getLongitude(),Toast.LENGTH_LONG).show();

                         tvlocation.setText(""+location.getAltitude()+" "+location.getLongitude());

                    }
                }
            });

I see as I understand that event addOnSuccessListener will happen whenever a new location is found or happens, because I want that event to happen once, because it is in the oncreate of the main activity, it will capture the location but until then no more that will be the last after I do not want more as it would be ?. thank you very much.

    
asked by Ijsud 01.09.2018 в 04:12
source

3 answers

-1

The addOnSuccessListener event only triggers when getLastLocation ( ) finds values to return, so addOnSuccessListener only listens to the return value of type Task getLastLocation () is not null to be able to give us onSuccess the values of the Location type.

This code is executed only once and is not listening all the time for changes, you can move and execute again the code that would update the location.

What I do update all the time is a onLocationChange , if you are going to listen when you change your position and give the values every time you do them (before passing some parameters to update it)

Translating the documentation for getLastLocation () You can make sure you do not update all the time with the following

  

If a location is not available, what should happen very   rarely, a null value will be returned. The best precision will be returned   available respecting the location permits.

     

This method provides a simplified way to obtain location.   It is especially suitable for applications that do not require a   precise location and who do not wish to maintain an additional logic for   Location updates.

    
answered by 02.09.2018 / 00:22
source
1

We declare a variable of type shared preference:

SharedPreferences preferencias = getSharedPreferences("Preferencias", MODE_PRIVATE); 

 mFusedLocationClient.getLastLocation() 
 .addOnSuccessListener(this, new OnSuccessListener<Location>() {
  @SuppressLint("SetTextI18n")
  @Override 
 public void onSuccess(Location location) { //Sabiendo que obtuvimos location, lo usamos

 boolean noRepetir = preferencias.getBoolean("noRepetir", false);

 if (!noRepetir){
 if (location != null) { 

 Toast.makeText(getApplicationContext(),"Latitud: " +location.getLatitude() + "Longitud: " + location.getLongitude(),Toast.LENGTH_LONG).show();
  tvlocation.setText(""+location.getAltitude()+" "+location.getLongitude()); 

 SharedPreferences.Editor editor = getSharedPreferences("Preferencias", MODE_PRIVATE).edit();
 editor.putBoolean("noRepetir", true);
 editor.apply();
        } 
    }
 }
 });

Well, it's a little more complicated. Now we declare a SharedPreference called preferences this will help us to save and access data saved as application data, so to understand the operation in the variable preferences I say getsharedpreference and I pass a name and a context that is int the name will be the container name of our data and the entire context is the type of access which you should only use private, after created when you create a variable under your code < strong> editor this edits the preferences, then I tell you to set a bool and pass it as parameters name and value of that field the name you use is noRepeat and the value is true and then I call to apply that edition, in other words I keep a Boolean value inside the preferences container inside the field called noRepetir and I set it to true .

This is what will help us: boolean noRepetir = preferencias.getBoolean("noRepetir", false); if you go a little higher you find that code. In this I declare a boolean variable noRepeat and this will get the value that is in the container preferences in the field noRepeat and as you see it receives 2 parameters ( name, default value) the name is the name of the field ie noRepeat and the default value is the value that is set if the field does not exist or does not contain any value.

After having obtained that value in our variable we ask that if it is false, the code is executed.

This should work in the following way the first time the activity starts the noRepetir field will not have an assigned value so by default the code will be executed in which the value of noRepetir will also be changed that is, we will keep a value in that field so when you try to execute the code again noRepeat will be true so it will not run again unless you delete the field within your preferences.

This I use for apps that require you to log in and I establish that you log in only once or until you log out so you do not have to be filling out the form every time you log in.

    
answered by 01.09.2018 в 04:52
1

From my point of view the best thing in your case would be to do the following in the interface that detects the new location call the method that disconnects and removes the listener I leave this class that is still under construction but works correctly, in it remove the LocationUpdate when finding the location, take a look I hope it works for you.

public class GoogleProviderLocation extends FusedLocationProviderClient{


GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
Location mLastLocation;
FusedLocationProviderClient mFusedLocationClient;
LocationCallback mLocationCallback;
Context context;
Activity activity;
GoogleLocationListener listener;

{
     mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            List<Location> locationList = locationResult.getLocations();
            if (locationList.size() > 0) {
                //The last location in the list is the newest
                Location location = locationList.get(locationList.size() - 1);
                Log.i("GoogleProviderLocation", "Location: " + location.getLatitude() + " " + location.getLongitude());
                mLastLocation = location;
                listener.OnLocationFound(location);
                disconnect();
                //Place current location marker
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
            }
        }
    };
}


public GoogleProviderLocation(@NonNull Context context,GoogleLocationListener listener,GoogleMap map) {
    super(context);
    this.context = context;
    this.listener = listener;
    this.mGoogleMap =map;
    Connect();
    Log.i("GoogleProviderLocation",mFusedLocationClient.toString());
}

public GoogleProviderLocation(@NonNull Activity activity,GoogleLocationListener listener) {
    super(activity);
    this.activity = activity;
    this.listener = listener;
    Connect();
}



@SuppressLint("MissingPermission")
public void Connect(){
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    if (mFusedLocationClient!=null)
        Log.i("Connected(): ",mFusedLocationClient.toString());

    Log.i("onMapReady() : "," "+mGoogleMap.getCameraPosition());

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(120000); // two minute interval
    mLocationRequest.setFastestInterval(120000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    mGoogleMap.setMyLocationEnabled(true);

}

public void disconnect(){
    if (mFusedLocationClient != null) {
        mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        Log.i("disconnected(): ",mFusedLocationClient.toString());
    }
}

public interface GoogleLocationListener{
    void OnLocationFound(Location location);
}

}

This GoogleLocationListener listener is to return the value to the activity that needs the location's data.

    
answered by 03.09.2018 в 17:14