gpt4 book ai didi

android - 如何使用新版本迁移 Android 首选项?

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:29 26 4
gpt4 key购买 nike

我有一个应用程序,我在其中存储这样的用户首选项:

public static final String KEY_PREFS_LOGIN_INFO = "login_info";
public static final String KEY_PREFS_FILE_VERSIONs = "file_versions";
public static final String KEY_PREFS_LOGS = "logs";
public static final String KEY_PREFS_OTHERS = "others";

使用像这样的特定于 pref 的方法:

public static void setFileVersion(String key) {
SharedPreferences settings = getAppContext().getSharedPreferences(KEY_PREFS_FILE_VERSIONS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("current", key);
editor.commit();
}

然后像这样检索值:

public static String filesVersion() {
SharedPreferences settings = getAppContext().getSharedPreferences(KEY_PREFS_FILE_VERSIONS, 0);
String current = settings.getString("current", "");
return current;
}

我想要做的是将我所有的首选项存储在一个位置,这样我就可以使用一种通用方法来访问它们中的任何一个。我如何设置一种方法,以便在升级时将值从旧存储位置迁移到新存储位置?我正在寻找类似于 SQLiteOpenHelper 中的 onUpgrade() 方法的东西。

最佳答案

我会覆盖应用程序。然后在启动时检查您的共享首选项中存储的版本号,然后根据需要执行从任何旧 key 到新 key 的遍历。

public class MyApplication extends Application {
private static final int CURRENT_PREFS_VERSION = 2;

@Override
public void onCreate() {
super.onCreate();

if(filesVersion() != CURRENT_PREFS_VERSION){
migrate(filesVersion())
}
}

private migrate(int oldVersion){

switch(oldVersion){
case 1:
//get old preference, store new preference
break;
}

setFileVersion(CURRENT_PREFS_VERSION)
}

关于android - 如何使用新版本迁移 Android 首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com