"Yes, "it’s possible, not as directly as you might be thinking.
1. Saving preferences in something concrete
Using the Objectoutputstream we can create a file with primitive data to be later read and transformed back into a Java object. The point here is to take all preferences and save in 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
}