6

I'm trying to backup/restore shared preferences of my app, I followed this step using Android Backup Service:

In Manifest.xml in <application> tag

<meta-data android:name="com.google.android.backup.api_key" android:value="My Key" />

added this class:

public class MyBackupAgent extends BackupAgentHelper {

    // The name of the SharedPreferences file
    static final String PREFS = "my_preferences";


    @Override
    public void onCreate() {
        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(Utilities.SETTINGS_KEY, helper);
    }

}

when set value to shared preference I do this:

BackupManager backupManager = new BackupManager(context);
backupManager.dataChanged();

But if I uninstall/reinstall app, changes doesn't apply...

Michele Lacorte
  • 5,323
  • 7
  • 32
  • 54

4 Answers4

4

My guess is you forgot to add

android:allowBackup="true"

inside your <application> tag in the AndroidManifest.xml file

amilcar-sr
  • 1,050
  • 9
  • 21
2

You have to allocate a helper and add it to the backup agent like this:

    @Override
public void onCreate() {
    FileBackupHelper helper = new FileBackupHelper(this,
            TOP_SCORES, PLAYER_STATS);
    addHelper(FILES_BACKUP_KEY, helper);
}

and also consider overriding onBackup() and onRestore() methods. See explanation here: https://developer.android.com/guide/topics/data/keyvaluebackup.html#BackupAgentHelper

Sagi Mymon
  • 958
  • 9
  • 12
1

when you call dataChanged() you just notify system that something is changed, it does not start backup in this moment, give it some time and wi fi connection. Check in your device's settings under 'Backup and reset' if 'automatic restore' is set.

Make sure that you writing to the same preferences (with the same key) which you are saving context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);

RadekJ
  • 2,835
  • 1
  • 19
  • 25
0

I assume you have setting something like this (depends on android version and even on the device)

"Cloud and Accounts"->"Backup and Restore"->"Automatic restoration"

turned on. If not, turning it on may solve your problem.

diidu
  • 2,823
  • 17
  • 32