2010-11-18 18 views
27

Tengo algunas preferencias compartidas (latitud, longitud) a las que quiero acceder desde un servicio, que no está subclasificado de Activity.Problemas al usar SharedPreferences en un servicio (getPreferences no existe en un servicio)

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

Mi objetivo aquí es permitir ESCRIBIR estas preferencias compartidas con mi servicio. ¿Alguna sugerencia/ejemplo que me pueda ayudar?

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 settings = this.getPreferences(MODE_WORLD_WRITEABLE);

Respuesta

43

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

+0

¿me puede explicar un poco más lo que tengo que cambiar en mi código para usar el administrador de preferencias? Estoy buscando en google pero no puedo encontrar información válida para mí – NullPointerException

+1

@ AndroidUser99: Reemplaza las llamadas a 'getPreferences()' con una llamada a 'PreferenceManager.getDefaultSharedPreferences()'. – CommonsWare

+0

intenté con esto: settings = PreferenceManager.getDefaultSharedPreferences (MODE_WORLD_WRITEABLE); pero me da un error, ¿qué estoy haciendo mal? – NullPointerException

1

Si ha declarado SharedPreferences como:

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

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

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

En misma manera incluso se puede guardar los valores de SharedPreferences.

2

Poco tarde para ayudarlo con esto, pero espero que esto ayude a alguien en el futuro. Aquí es su problema:

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

Dado que sólo recuperar el archivo de preferencias compartido cuando se crea el servicio, el archivo no 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 cualquier dato que pueda haber cambiado, asegúrese de recuperar el archivo de preferencias compartido (recarga) de nuevo como:

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 su aplicación:

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

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

 settings = this.getPreferences(MODE_MULTI_PROCESS); 
19

en realidad, la mayoría de ustedes se esté ejecutando en el p Obviamente, en dispositivos con API> = 11, las preferencias compartidas ya no están configuradas para el uso de procesos múltiples por defecto.

Solución:

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

Según el comentario en la respuesta de @CommonsWare, ¿cómo se puede hacer esto con '' PreferenceManager.getDefaultSharedPreferences() ''? Estoy en un servicio y no sé el nombre de mis preferencias compartidas predeterminadas. – gozzilli

+0

Realmente me salvas. Gracias, muchtttttttttttttttttt –

+0

'MODE_MULTI_PROCESS' ha quedado obsoleto en la API 23. Consulte http://developer.android.com/reference/android/content/Context.html#MODE_MULTI_PROCESS –

1

Para las personas que toparse con esto ... Yo tenía un problema similar ... La verdadera causa del problema es que estamos tratando de obtener/utilizar un contexto que no es totalmente Inicializado ... Pude usar sharedPreferences normalmente fuera de mi constructor para mi IntentService.

Cuestiones relacionadas