Estou a desenvolver uma aplicação onde preciso de retirar o local atual do utilizador, o problema é que o código que desenvolvi devolve-me as ultimas coordenadas existentes no dispositivo e eu só queria as atuais mas nem sempre obtem só depois de a minha posiçao mudar é que obtenho coordenadas atuais , alguma sugestão para obter a localização atual do utilizador de maneira mais pratica? Ainda tentei forçar o resultado com um for para evitar ter a ultima localização mas não resolve o problema.
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;
}
}
});
}
}
}