LocationManager always picking up the latest Android Location

0

In my app I use Direction and Google Maps. So far it's working. The application opens the MainActivity, and when it is necessary for the user to trace the route, calls another Activity (where the Google Maps Direction programming is). So far so good, but if the user moves from location and open the application, and choose any route or even it, it maps based on the last location. If it closes the activity and reopens, then yes it takes the current position. I'm using getLastKnownLocation(LocationManager.GPS_PROVIDER); I think it might be the reason for this, but I did not find a way to replace it.

My Map and Direction class

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener {

    private GoogleMap mMap;
    private String enderecoLugar;
    double lat = 0.0;
    double lng = 0.0;
    private String[] permissoesNecessarias = new String[]{
            android.Manifest.permission.ACCESS_FINE_LOCATION
    };
    private List<Marker> originMarkers = new ArrayList<>();
    private List<Marker> destinationMarkers = new ArrayList<>();
    private List<Polyline> polylinePaths = new ArrayList<>();
    private ProgressDialog progressDialog;
    private Address enderecoUsuario;
    private String origemDispositivo;
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        Permissoes.validaPermissoes(2, this, permissoesNecessarias);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //recuperando dados da main principal
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            enderecoLugar = bundle.getString("endereco");
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        minhaLocalizacao();
    }

    @Override
    public void onDirectionFinderStart() {

        progressDialog = ProgressDialog.show(this, "Aguarde.",
                "Procurando rota..!", true);

        if (originMarkers != null) {
            for (Marker marker : originMarkers) {
                marker.remove();
            }
        }
        if (destinationMarkers != null) {
            for (Marker marker : destinationMarkers) {
                marker.remove();
            }
        }
        if (polylinePaths != null) {
            for (Polyline polyline : polylinePaths) {
                polyline.remove();
            }
        }
    }

    @Override
    public void onDirectionFinderSuccess(List<Route> routes) {
        progressDialog.dismiss();
        polylinePaths = new ArrayList<>();
        originMarkers = new ArrayList<>();
        destinationMarkers = new ArrayList<>();

        Log.i("Origem", String.valueOf(originMarkers));
        Log.i("Destino", String.valueOf(destinationMarkers));
        for (Route route : routes) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
            ((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
            ((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);

            originMarkers.add(mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
                    .title(route.startAddress)
                    .position(route.startLocation)));
            destinationMarkers.add(mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
                    .title(route.endAddress)
                    .position(route.endLocation)));

            PolylineOptions polylineOptions = new PolylineOptions().
                    geodesic(true).
                    color(Color.BLUE).
                    width(10);

            for (int i = 0; i < route.points.size(); i++)
                polylineOptions.add(route.points.get(i));

            polylinePaths.add(mMap.addPolyline(polylineOptions));
        }
    }

    public void minhaLocalizacao() {

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
                        PackageManager.PERMISSION_GRANTED) {
        } else {

            mMap.setMyLocationEnabled(true);
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            atualizarLocalizacao(location);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locListener);

            String origem = origemDispositivo;
            String destino = enderecoLugar;
            if (origem == null || destino == null) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setTitle("Fora de Comunicação");
                dialog.setIcon(R.drawable.ic_maps);
                dialog.setMessage("Ative o GPS e a Internet do seu dispositivo, para que " +
                        "possamos traçar a rota para você.");
                dialog.setCancelable(false);
                dialog.setPositiveButton("Voltar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                dialog.create();
                dialog.show();
            } else {

                try {
                    new DirectionFinder(this, origem, destino).execute();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        for (int resultado : grantResults) {
            if (resultado == PackageManager.PERMISSION_DENIED) {
                alertaValidacaoPermissao();

            } else if (resultado == PackageManager.PERMISSION_GRANTED) {
                minhaLocalizacao();
            }
        }
    }

    private void alertaValidacaoPermissao() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Permissão de uso");
        builder.setCancelable(false);
        builder.setMessage("Para usar o Google Maps você precisa aceitar a permissão ");
        builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.create();
        builder.show();
    }


    public void atualizarLocalizacao(Location location) {

        if (location != null) {

            lat = location.getLatitude();
            lng = location.getLongitude();

            try {
                enderecoUsuario = buscarEndereco(lat, lng);
                origemDispositivo = enderecoUsuario.getAddressLine(0) + " "
                        + enderecoUsuario.getAddressLine(1) + ", "
                        + enderecoUsuario.getPostalCode();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    LocationListener locListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            atualizarLocalizacao(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    private Address buscarEndereco(double lat, double lng) throws IOException {

        Geocoder geocoder;
        Address address = null;
        List<Address> addresses;

        geocoder = new Geocoder(getApplicationContext());

        addresses = geocoder.getFromLocation(lat, lng, 1);
        if (addresses.size() > 0) {
            address = addresses.get(0);
        }
        return address;
    }
}
    
asked by anonymous 20.07.2017 / 00:55

1 answer

0

You should change your logic to run DirectionFinder also when LocationListener.onLocationChanged() is invoked.

In this way, if it changes position the route will be recalculated.

    
20.07.2017 / 01:58