I'm developing an application where I need to remove the current location of the user, the problem is that the code I developed returns me the last coordinates in the device and I just wanted the current ones but not always only after mine position change is that I get current coordinates, any suggestions to get the current location of the user more practically? I've still tried to force the result with a for to avoid having the last location but it does not solve the problem.
private TextView txtLatitude;
private TextView txtLongitude;
public Button btcoordenadas;
private Location location;
private Location mCurrentLocation ;
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLongitude = (TextView) findViewById(R.id.txtLongitude);
btcoordenadas = (Button) findViewById(R.id.btncoordenadas);
final double[] latitude = {0.0};
final double[] longitude = {0.0};
final LocationManager[] locationManager = {(LocationManager) this.getSystemService(Context.LOCATION_SERVICE)};
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
for(int i=0; i<=10; i++) {
mCurrentLocation = location;
updateUI();
makeUseOfNewLocation(location);
}
}
private void updateUI() {
txtLatitude.setText(String.valueOf(mCurrentLocation.getLatitude()));
txtLongitude.setText(String.valueOf(mCurrentLocation.getLongitude()));
}
private void makeUseOfNewLocation(Location location) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Solicitar permissão ao usuário.
}
else {
btcoordenadas.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int l=0; l<=10; l++) { switch (v.getId()) {
case R.id.btncoordenadas:
if (locationManager[0].isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager[0] = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager[0].requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 600, 0, locationListener);
location = locationManager[0].getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
else {
Log.i("Erro", "A internet não se encontra ligada");
}
}
break;
}
}
});
}
}
}