Pregunta

Estoy tratando de habilitar/deshabilitar los servicios GPS por un ToggleButton. La aplicación comienza con el botón sin control, y los servicios GPS están deshabilitados (como deberían ser). Se encienden con éxito y funcionan muy bien PERO Cuando lo apago de nuevo, se bloquea. Aquí está el código:

    final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    final LocationListener locationListener = null;
    final ToggleButton gpsButton = (ToggleButton) findViewById(R.id.gpsButton);


    gpsButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (gpsButton.isChecked()) {
                 LocationListener locationListener = new LocationListener() {
                    public void onLocationChanged(Location location) {
                      // Called when a new location is found by the network location provider.

                        //doing some stuff with locations


                    }

                    public void onStatusChanged(String provider, int status, Bundle extras) {}

                    public void onProviderEnabled(String provider) {}

                    public void onProviderDisabled(String provider) {}
                  };
                  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, seconds, 0, locationListener);
            }
            else {
                locationManager.removeUpdates(locationListener);
            }
        }
¿Fue útil?

Solución

Estás declarando el locationListener fuera de la onClickListener, pero luego creando un nuevo local locationListener variable Cuando el usuario hace clic en el botón.

Aún es null Cuando intenta eliminar las actualizaciones porque ha creado una variable diferente. Eliminar la declaración de tipo de locationListener en el onClick método, entonces se convierte en

...
if (gpsButton.isChecked()) {
    locationListener = new LocationListener() {
    ...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top