Problemas en el uso SharedPreferences en un Servicio (getPreferences no existe en un servicio)

StackOverflow https://stackoverflow.com/questions/4214939

Pregunta

Tengo algunas preferencias compartidas (latitud, longitud) que desea acceder desde un servicio, que no es una subclase de la actividad.

En particular, cuando intento getPreferences de acceso, esta función no existe en el de un servicio. Mi código se publica a continuación

Mi objetivo aquí es permitir escribir estas preferencias compartidas con mi servicio. Cualquier sugerencia / ejemplos que me puedan ayudar a lo largo de?

public class MyService extends Service implements Runnable {

    LocationManager mLocationManager;
    Location mLocation;
    MyLocationListener mLocationListener;
    Location currentLocation = null;
    static SharedPreferences settings;
    static SharedPreferences.Editor configEditor;

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        settings = this.getPreferences(MODE_WORLD_WRITEABLE);
        configEditor = settings.edit();
        writeSignalGPS();
    }

    private void setCurrentLocation(Location loc) {
        currentLocation = loc;
    }

    private void writeSignalGPS() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Looper.prepare();
            mLocationListener = new MyLocationListener();
            mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 1000, 0, mLocationListener);
            Looper.loop();
            //Looper.myLooper().quit();
        } else {
            Toast.makeText(getBaseContext(),
              getResources().getString(R.string.gps_signal_not_found),
              Toast.LENGTH_LONG).show();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (currentLocation!=null) {
                configEditor.putString("mylatitude", ""+currentLocation.getLatitude());
                configEditor.putString("mylongitude", ""+currentLocation.getLongitude());
                configEditor.commit();
            }
        }
    };

    private class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                Toast.makeText(getBaseContext(),
                getResources().getString(R.string.gps_signal_found),
                  Toast.LENGTH_LONG).show();
                setCurrentLocation(loc);
                handler.sendEmptyMessage(0);
            }
        }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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

Me sale el error en la línea de settings = this.getPreferences(MODE_WORLD_WRITEABLE);

¿Fue útil?

Solución

Si sólo está utilizando uno SharedPreferences para su aplicación, tiene todos el código de conseguirlo a través de PreferenceManager.getDefaultSharedPreferences().

Otros consejos

En realidad, la mayoría de ustedes se esté ejecutando en el problema, que en los dispositivos con API> = 11, las preferencias compartidas no están establecidos para el uso de varios procesos de forma predeterminada más.

Solución:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    prefs = getSharedPreferences(PREFS, 0 | Context.MODE_MULTI_PROCESS);
} else {
    prefs = getSharedPreferences(PREFS, 0);
}

Un poco tarde para ayudarle a salir de esto, pero espero que esto ayude a alguien en el futuro. Aquí está el problema:

    public void onCreate() {
       settings = this.getPreferences(MODE_WORLD_WRITEABLE);
       configEditor = settings.edit();
       writeSignalGPS();
    }

Dado que sólo recuperar el archivo de preferencias compartidas cuando se crea el servicio, el archivo nunca se actualiza correctamente por el servicio y por lo tanto los datos nunca se comparte con la aplicación. Antes de grabar en Preferencias compartidas o recuperar los datos que pueden haber cambiado, asegúrese de recuperar el archivo Preferencia compartida (recarga) de nuevo como por ejemplo:

    private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (currentLocation!=null) {
            settings = this.getPreferences(MODE_WORLD_WRITEABLE);
            configEditor = settings.edit();
            configEditor.putString("mylatitude", ""+currentLocation.getLatitude());
            configEditor.putString("mylongitude", ""+currentLocation.getLongitude());
            configEditor.commit();
        }
    }

A continuación, en la aplicación:

     settings = this.getPreferences(MODE_WORLD_WRITEABLE);
     String myLat = setttings.getString("mylatitude","");

Además, nada en Android 3.0 que tiene un escenario donde un servicio y una cuota de actividad Preferencias compartidas, debe utilizar:

     settings = this.getPreferences(MODE_MULTI_PROCESS);

Si ha declarado SharedPreferences como:

private static final String PREFS_NAME = "UserData"; 
private static final String PREFS_VALUE1 = "value1"; 

a continuación, utilizar el siguiente código a buscar valores:

SharedPreferences preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
value1 = preferences.getString(PREFS_VALUE1, "0");

En misma manera Incluso puede guardar los valores a SharedPreferences.

Para las personas que toparse con esto ... que tenía un problema similar ... La verdadera causa del problema es que estamos tratando de obtener / utilizar un contexto que no se ha inicializado completamente .. yo era capaz de utilizar normalmente SharedPreferences fuera de mi constructor para mi IntentService.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top