0

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;
                }


            }
        });

    }

}

    }
0

1 Resposta 1

0

Para isso você pode usar o FusedLocationProviderApi que está incluso no pacote do PlayServices. Com essa api do Google você consegue de forma rápida obter a localização do usuário, mudanças de localização e o mais importante o controle do uso da Bateria com as Flags PRIORITY_HIGH_ACCURACY , PRIORITY_LOW_POWER,PRIORITY_NO_POWER , informações sobre as flags.
Não vou colocar um exemplo de implementação pois acho que os links e o exemplo da documentação do Google já é o bastante para você conseguir estudar e adaptar ao seu código.Estou deixando também para você todo o código do google utilizando a api tudo no GitHub. Demo GitHub Google

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .