在我的BackupAgentHelper中,我需要知道标准首选项文件的名称。我认为"getPreferenceManager().getSharedPreferencesName()"是个好主意,但似乎我无法获得上下文。
如何获取标准首选项文件的名称和/或首选项管理器的方法?
public class MyBackupAgentHelper extends BackupAgentHelper {
private static final String TAG_PREFERENCES = "preferences";
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, this
.getPreferenceManager().getSharedPreferencesName());
addHelper(TAG_PREFERENCES, helper);
}
}
API缺乏简单的方法。我这样做是为了避免硬编码任何东西。
final public class BackupAgent extends BackupAgentHelper
{
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
public void onCreate()
{
String packageName = "???";
try {
// read current version information about this package
Context context = getApplicationContext();
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
// preference file name is <package_name>_preferences
packageName += "_preferences";
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, packageName);
addHelper(PREFS_BACKUP_KEY, helper);
} catch (Exception e) {
e.printStackTrace();
}
}
}