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.