我想在SharedPreferences中备份一个值,以便我可以在重新安装后读出这个值.
MyBackupAgent
package com.app.appname;
import android.app.backup.BackupAgentHelper;
import android.app.backup.BackupManager;
import android.app.backup.SharedPreferencesBackupHelper;
import android.content.Context;
public class MyBackupAgent extends BackupAgentHelper{
static final String PREFS_DISPLAY = "AppName";
private Context context;
static final String MY_PREFS_BACKUP_KEY = "keyToStore";
public MyBackupAgent(Context context){
this.context = context;
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(context,PREFS_DISPLAY);
addHelper(MY_PREFS_BACKUP_KEY,helper);
}
public void storeData(){
BackupManager backupManager = new BackupManager(context);
backupManager.dataChanged();
}
}
我如何存储数据:
...
SharedPreferences settings = getSharedPreferences("AppName",0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("keyToStore",true);
editor.commit();
new MyBackupAgent(this).storeData();
...
我如何收到数据:
...
SharedPreferences settings = getSharedPreferences("AppName",0);
boolean value = settings.getBoolean("keyToStore",false);
...
我还在Android Manifest中添加了API:
你知道我做错了什么以及它是如何工作的吗?它真的有效吗?
最佳答案
您的SharedPreferences备份代理类应该是这样的:
public class MyPrefsBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "user_preferences";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,PREFS);
addHelper(PREFS_BACKUP_KEY,helper);
}
}
然后,您必须使用以下内容请求云备份(它将完成异步):
import android.app.backup.BackupManager;
...
public void requestBackup() {
BackupManager bm = new BackupManager(this);
bm.dataChanged();
}
并且您不需要手动还原SharedPreferences,因为它们由SharedPreferencesBackupHelper类自动管理.
除了备份API密钥之外,请不要忘记在清单中添加备份代理类:
有关这一切的更多信息,请参见http://developer.android.com/guide/topics/data/backup.html和http://developer.android.com/training/cloudsync/backupapi.html