feat: 添加 SharedPreferences 管理类

- 实现配置加载和保存功能
- 使用 Gson 序列化文件夹列表
- 支持保存和读取最后显示的壁纸 URI

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-20 23:54:29 +08:00
1 parent ae29ac8255
commit 9d6b34cde7
1 file changed
+73
@@ -0,0 +1,73 @@
package cn.hugh.bz.gk2.wallpaper;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import cn.hugh.bz.gk2.model.AppConfig;
import cn.hugh.bz.gk2.model.PlayMode;
public class WallpaperPreferences {
private static final String PREFS_NAME = "wallpaper_prefs";
private static final String KEY_FOLDERS = "selected_folders";
private static final String KEY_PLAY_MODE = "play_mode";
private static final String KEY_INTERVAL = "interval_minutes";
private static final String KEY_ENABLED = "enabled";
private static final String KEY_CURRENT_INDEX = "current_index";
private static final String KEY_LAST_URI = "last_uri";
private final SharedPreferences prefs;
private final Gson gson;
public WallpaperPreferences(Context context) {
this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.gson = new Gson();
}
public AppConfig loadConfig() {
AppConfig config = new AppConfig();
String foldersJson = prefs.getString(KEY_FOLDERS, null);
if (foldersJson != null) {
Type listType = new TypeToken<ArrayList<String>>(){}.getType();
List<String> folders = gson.fromJson(foldersJson, listType);
config.setSelectedFolders(folders);
}
String modeString = prefs.getString(KEY_PLAY_MODE, PlayMode.SEQUENTIAL.name());
config.setPlayMode(PlayMode.valueOf(modeString));
config.setIntervalMinutes(prefs.getInt(KEY_INTERVAL, 30));
config.setEnabled(prefs.getBoolean(KEY_ENABLED, false));
config.setCurrentIndex(prefs.getInt(KEY_CURRENT_INDEX, 0));
return config;
}
public void saveConfig(AppConfig config) {
SharedPreferences.Editor editor = prefs.edit();
String foldersJson = gson.toJson(config.getSelectedFolders());
editor.putString(KEY_FOLDERS, foldersJson);
editor.putString(KEY_PLAY_MODE, config.getPlayMode().name());
editor.putInt(KEY_INTERVAL, config.getIntervalMinutes());
editor.putBoolean(KEY_ENABLED, config.isEnabled());
editor.putInt(KEY_CURRENT_INDEX, config.getCurrentIndex());
editor.apply();
}
public void saveLastUri(String uri) {
prefs.edit().putString(KEY_LAST_URI, uri).apply();
}
public String getLastUri() {
return prefs.getString(KEY_LAST_URI, null);
}
}