【问题标题】:change default preference on upgrade更改升级时的默认首选项
【发布时间】:2016-09-15 11:05:47
【问题描述】:

在我的应用程序中,我有以下代码告诉我是否默认启用了一项功能:

public boolean getFeatureEnabled()
{
    return mPrefs.getBoolean("FEATURE_ENABLED", DEFAULT_ENABLED);
}

仅当用户从 UI 更改设置时,此首选项才会被覆盖。所以默认情况下,它从DEFAULT_ENABLED 中提取值,这是某处的类变量。

在当前版本中,DEFAULT_ENABLEDtrue,但在我的应用程序的下一个版本中,false

问题是更新后,使用上面的代码,没有从 UI 更改默认设置的老用户将禁用他们的功能 - 我想避免这种情况。

关于如何处理这个问题的任何建议?

【问题讨论】:

    标签: android sharedpreferences upgrade


    【解决方案1】:

    据我了解,您有一项默认启用的功能,但除非用户明确更改,否则此默认设置从未写入SharedPreferences。 现在您希望默认禁用该功能,但不影响已启用该功能的用户的行为。

    我能想到 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 如果您不这样做,则仍有希望。您可以使用in this StackOverflow answer 给出的答案来检查这是否是您的第一次安装

    选项 3 您可以发布应用的中间版本,该版本的行为与现在一样,但将未保存的默认设置保存在 SharedPreferences 中。这将使热切的用户保持原样的功能,但您必须等到大部分用户更新后才能发布所需的行为。

    【讨论】:

      【解决方案2】:

      在新版本的preferences 中将另一个标志“FIRST_TIME”设置为“true”。检查应用的第一个屏幕

      if(FIRST_TIME==true)
       {
       //put FEATURE_ENABLED = false;
       //put FIRST_TIME = false;
      
       }
      

      通过这样做,FEATURE_ENABLED 将在用户首次启动应用程序时设置为 false,并且不会考虑默认值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多