处理许多 SharedPreferences 的替代方案

Alternatives to deal with many SharedPreferences

我正在开发一个使用大量 SharedPreferences 的 Android 应用程序。我有几个 SharedPreferences 文件,我在整个应用程序中对这些文件进行了多达 77 次调用。有时我使用 :

static final String FileName= "SharedPreferencesFile";

在我的活动开始时 :

SharedPreferences settings = getSharedPreferences(FileName, Context.MODE_PRIVATE);

每当我需要使用它们时。有时我只是直接引用文件,如:

 SharedPreferences settings = getSharedPreferences("SharedPreferencesFile", Context.MODE_PRIVATE);

我现在正在努力组织事情,所以我想了解不同的替代方法。我的问题是:

  1. 我应该为我的应用程序中的所有变量定义一个 "SharedPreferencesFile" 还是像我现在所做的那样使用多个文件?
  2. 我是否应该在我的应用程序资源文件夹中的 strings.xml 中定义所有这些 String FileName= "SharedPreferencesFile",而不是将它们放在我的活动的开头,而只是将它们用作 SharedPreferences settings = getSharedPreferences(R.string.SharedPreferencesFile, Context.MODE_PRIVATE);
  3. 我是否应该按照 Android Shared Preferences
  4. 中的建议创建一个助手 class 来处理每个 activity 的所有共享首选项调用

创建一个单例 class 来处理你所有的偏好,理想情况下你应该为每个偏好设置一个 getter 和 setter 并且你只会做:

Preferences.getInstance().getSomePref();

Preferences.getInstance().setSomePref(value);

Should I define a single "SharedPreferencesFile" for all the variables in my app or using multiple files as I'm doing now is ok?

如果你能以合乎逻辑的方式对它们进行分类,那就去做吧。不要只是为了让它们以随机方式拆分多个文件而这样做。以后会引起很多混乱

Should I define all these String FileName= "SharedPreferencesFile" in the strings.xml from my app resources folder instead of putting them at the beginning of my activities and the just use them as SharedPreferences settings = getSharedPreferences(R.string.SharedPreferencesFile, Context.MODE_PRIVATE);

将字符串资源提取到 strings.xml 总是好的。如果您要添加翻译,请小心并确保您不翻译名称。将它们标记为 notranslate 字符串资源。

Should I create a helper class that handles all shared preferences calls for every activity as suggested in Android Shared Preferences

已经有几个可用的。这是我为简化 SharedPreferences 的使用而创建的一个。它是开源的,只需添加 gradle 依赖即可使用 - Android-SharedPreferences-Helper

每次通话都可以使用相同的 SharedPreferences

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

String get(String key)void set(String key) 构建包装助手 class 会很容易。

类似于

class MyPrefs {

  static MyPrefs instance;

  static synchronized getInstance(Context ctx) {
     if(instance == null) {
        instance = PreferenceManager.getDefaultharedPreferences(ctx);
     }
     return instance;

  }

  //then getters and setters e.g.
  int getInt(String key, int defVal) {
     return Integer.valueOf(getString(key))
  }

  String get(String key) {
    return instance.getString(key);
  }
}