Android - Share Preferences for another device

1

My question is: Can you share information saved by SharedPrefences to another device, either by bluetooth or another connection?

MainActivity.java:

SharedPreferences.EDITOR editor = getSharedPreferences("pref", MODE_PRIVATE).edit();
editor.putString("value1", "example");
editor.commit();
    
asked by anonymous 08.05.2018 / 20:52

1 answer

1

"Yes," it is possible, not as directly as you may be thinking.

1. Save preferences in something concrete

Using the ObjectOutputStream we can create a file with primitive data for later be read and transformed back into a Java object. The point here is to get all preferences and save to a Map (since they are keys and values) using the SharedPreferences.getAll ()

File prefsFile = new File(getExternalFilesDir(null), "prefs.bak");
if (!prefsFile.exists()) {
    if (!prefsFile.createNewFile())
        // Falha ao criar arquivo
}

try {
    SharedPreferences prefs = getSharedPreferences("pref", MODE_PRIVATE);
    ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(prefsFile));
    output.writeObject(prefs.getAll());
    output.flush();
    output.close();
} catch (IOException e) {
    // Falha ao escrever no arquivo
}

2. Send prefs.bak to the other device

Well, there are several ways to do this. Once submitted, be aware of the file path.

3. Read and apply prefs.bak on the other device

Assuming both devices run your app:

File prefsFile = new File("caminho/para/o/prefs.bak");
if (prefsFile.exists()) {
    try {
        SharedPreferences.Editor editor = getSharedPreferences("pref", MODE_PRIVATE).edit();
        ObjectInputStream input = new ObjectInputStream(new FileInputStream(prefsFile));
        // Ler o objeto como um mapa
        Map<String, ?> entries = (Map<String, ?>) input.readObject();
        // Na falta de um método "putAll()" vamos dar um loop no mapa e pra cada entry, fazemos um apply()
        for (Map.Entry<String, ?> entry : entries.entrySet()) {
            Object o = entry.getValue();
            String key = entry.getKey();

            if (o instanceof Boolean)
                editor.putBoolean(key, (Boolean) o);
            else if (o instanceof Float)
                editor.putFloat(key, (Float) o);
            else if (o instanceof Integer)
                editor.putInt(key, (Integer) o);
            else if (o instanceof Long)
                 editor.putLong(key, (Long) o);
            else if (o instanceof String)
                 editor.putString(key, ((String) o));
            }
            // Finalmente aplique os novos valores importados
            editor.apply();
    } catch (ClassNotFoundException | IOException ex) {
         // Falha ao ler arquivo
    }
} else {
    // Arquivo não encontrado
}
    
09.05.2018 / 21:33