Problemas usando SharedPreferências em um serviço (GetPreferences não existe em um serviço)

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

Pergunta

Tenho algumas preferências compartilhadas (latitude, longitude) que quero acessar de um serviço, que não é subclassificado da atividade.

Em particular, quando tento acessar o GetPreferences, essa função não existe em um serviço. Meu código está postado abaixo

Meu objetivo aqui é permitir escrever essas preferências compartilhadas com meu serviço. Alguma sugestão/exemplos que podem me ajudar?

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) {}
}

Eu recebo o erro na linha settings = this.getPreferences(MODE_WORLD_WRITEABLE);

Foi útil?

Solução

Se você está usando apenas um SharedPreferences para o seu aplicativo, tenha tudo Seu código obtenha -o via PreferenceManager.getDefaultSharedPreferences().

Outras dicas

Na verdade, a maioria de vocês pode estar enfrentando o problema, que em dispositivos com API> = 11, as preferências compartilhadas não estão mais definidas para o uso de vários processos por padrão.

Solução:

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

Um pouco atrasado para ajudá -lo, mas espero que isso ajude alguém no futuro. Aqui está o seu problema:

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

Como você recupera apenas o arquivo de preferência compartilhada quando o serviço é criado, o arquivo nunca é atualizado corretamente pelo serviço e, portanto, os dados nunca são compartilhados com o aplicativo. Antes de escrever para preferências compartilhadas ou recuperar quaisquer dados que possam ter mudado, recupere novamente o arquivo de preferência compartilhada (recarregue), 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();
        }
    }

Então, em seu aplicativo:

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

Além disso, qualquer coisa no Android 3.0 que tenha um cenário em que um serviço e uma atividade compartilhem prefs compartilhados, você deve usar:

     settings = this.getPreferences(MODE_MULTI_PROCESS);

Se você declarou Preferências Compartilhadas Como:

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

Em seguida, use o código abaixo para buscar valores:

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

Da mesma forma, você pode até salvar valores em superestres compartilhadas.

Para as pessoas que se deparam com isso ... eu tive um problema semelhante ... a verdadeira causa do problema é que estamos tentando obter/usar um contexto que não é totalmente inicializado. Consegui usar aspreferências compartilhadas normalmente fora do meu Construtor para o meu serviço de intenção.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top