Android 在升级时更改默认首选项
在我的应用程序中,我有以下代码,告诉我是否默认启用了某项功能:Android 在升级时更改默认首选项,android,sharedpreferences,upgrade,Android,Sharedpreferences,Upgrade,在我的应用程序中,我有以下代码,告诉我是否默认启用了某项功能: public boolean getFeatureEnabled() { return mPrefs.getBoolean("FEATURE_ENABLED", DEFAULT_ENABLED); } 仅当用户从UI更改设置时,此首选项才会被覆盖。因此,默认情况下,它从default\u ENABLED中提取其值,这是某个类变量 在当前版本中,DEFAULT\u ENABLED为true,但在我的应用程序的下一个版本中将为
public boolean getFeatureEnabled()
{
return mPrefs.getBoolean("FEATURE_ENABLED", DEFAULT_ENABLED);
}
仅当用户从UI更改设置时,此首选项才会被覆盖。因此,默认情况下,它从default\u ENABLED
中提取其值,这是某个类变量
在当前版本中,DEFAULT\u ENABLED
为true
,但在我的应用程序的下一个版本中将为false
问题是,在更新之后,使用上面的代码,没有从UI更改默认设置的老用户将禁用其功能-我希望避免这种情况
关于如何处理这个问题,有什么建议吗?在新版本的首选项中,将另一个标记“首次
”作为“真”
”。查看应用程序的第一个屏幕
if(FIRST_TIME==true)
{
//put FEATURE_ENABLED = false;
//put FIRST_TIME = false;
}
通过这样做,第一次用户启动应用程序,并将不考虑默认值,因为您有一个默认启用的特性,但除非用户明确更改,否则默认不会写入<代码> SydPraseP< <代码>。
现在,您希望在默认情况下禁用该功能,但不影响已启用该功能的用户的行为
我可以想出3种选择:
选项1如果您已经保存了最新版本,可以在迁移逻辑中检查:
private void migratePreferences(Context context) {
SharedPreferences prefs = context.getSharedPreferences("your_preference_file", MODE_PRIVATE);
int lastKnownVersionCode = (prefs.getInt("LAST_INSTALLED_VERSION", BuildConfig.VERSION_CODE);
prefs.edit().putInt("LAST_INSTALLED_VERSION", BuildConfig.VERSION_CODE).apply();
//this is the old featureEnabled check
boolean oldPreferenceValue = prefs.getBoolean("FEATURE_ENABLED", true);
boolean newPreferenceValue;
if (prefs.contains("FEATURE_ENABLED")) {
//the feature was modified by the user so respect their preference
newPreferenceValue = prefs.getBoolean("FEATURE_ENABLED", false);
} else if (lastKnownVersionCode == BUGGY_VERSION_WITH_FEATURE_ENABLED_BY_DEFAULT) {
//the user is updating from the buggy version.
// this check could include a range of versions if you've released several buggy versions.
// this is also where option 2 would be inserted
newPreferenceValue = oldPreferenceValue;
} else {
//the new default that will apply to fresh installs
newPreferenceValue = false;
}
//save the preference
prefs.edit().putBoolean("FEATURE_ENABLED", newPreferenceValue).apply();
}
然而,这取决于你的已经在你的应用程序启动代码中调用了这个方法
选项2如果您不这样做,仍然有希望。您可以使用给出的答案检查这是否是您的第一次安装
选项3您可以发布应用程序的中间版本,其行为与现在相同,但将未保存的默认设置保存在SharedReferences
中。这将保持该功能与您渴望的用户一样,但您必须等到大部分用户更新后才能发布所需的行为