Android使用备份代理保存共享首选项

时间:2016-04-03 08:19:59

标签: android sharedpreferences android-backup-service

在我的backupagent课程中,我有这个:

import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;

public class TheBackupAgent extends BackupAgentHelper {
    // The names of the SharedPreferences groups that the application maintains.  These
    // are the same strings that are passed to getSharedPreferences(String, int).
    static final String RECIPE_NAMES = "MyRecipeNames";
    static final String TEST = "testSave";

    // An arbitrary string used within the BackupAgentHelper implementation to
    // identify the SharedPreferencesBackupHelper's data.
    static final String MY_PREFS_BACKUP_KEY = "myprefs";

    // Simply allocate a helper and install it
    public void onCreate() {
        SharedPreferencesBackupHelper helper =
                new SharedPreferencesBackupHelper(this, TEST);
        addHelper(MY_PREFS_BACKUP_KEY, helper);
    }
}

然后我有代码将字符串存储到testSave共享首选项中并请求备份首选项:

public void requestBackup() {
    BackupManager bm = new BackupManager(this);
    bm.dataChanged();
}

public void saveRecipe (View v) {

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("testSave", 0);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("testString", "This is my saved data.");
    editor.apply();

    requestBackup();
}

然后我尝试卸载并重新安装应用程序,保存的数据消失了。我已将所需的代码添加到Manifest但它无效。我的应用程序是否需要在Play商店中?我真的不知道为什么它不起作用。

1 个答案:

答案 0 :(得分:0)

您可以使用bmgr工具测试您的备份代理,该工具是Android SDK的一部分(它是adb中的命令)。 See here how it can be used.

相关问题