【发布时间】:2014-06-12 15:25:20
【问题描述】:
我正在使用 App Widget Configuration Activity 为我的小部件设置一些设置。当用户确认后,通过调用 saveWidgetConfig(Config) 将设置保存到 Sharedpreferences。稍后当接收到刷新小部件的广播时(第一个警报在 1000 毫秒后),通过调用 loadWidgetConfig(id) 再次加载配置。请参阅下面的简单实现。
现在的问题是,即使我
调用 editor.apply()(或 commit() - 不会改变任何东西)
不要使用静态类 => 每次创建对象时: 新的小部件配置(上下文)
当尝试从我的接收器类访问 SharedPreferences 时,它不包含对给定键的任何偏好。
但是:
- 如果我尝试在应用/提交后直接访问首选项,它可以工作 - 即使我创建了一个新的 WidgetConfiguration 类
- 在我重新启动设备或从 ecipse 运行新版本后它也可以工作
所以我认为它与不同的上下文有关,或者我得到了 Sharedpreferences 的不同“版本”。但是直到现在(三个多小时!!!)我都无法弄清楚...... :-(
public class WidgetConfiguration {
private SharedPreferences prefs;
private String LOG_TAG = this.getClass().getSimpleName();
public WidgetConfiguration(Context context) {
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public static String KEY_WIDGET_CONFIG = "single_widget_object_config_";
public void saveWidgetConfig(Widget widget) {
Gson gson = new Gson();
String json = gson.toJson(widget);
Editor editor = prefs.edit();
editor.putString(KEY_WIDGET_CONFIG + widget.getAppwidgetID(), json);
Log.d(LOG_TAG, "saved widget id " + widget.getAppwidgetID() + "\n" + json);
editor.apply();
};
public Widget loadWidgetConfig(int appwidgetID) {
Widget loadedWidget = null;
String key = KEY_WIDGET_CONFIG + appwidgetID;
if (prefs.contains(key))
{
String json = prefs.getString(key, null);
Log.d(LOG_TAG, "loaded widget id " + appwidgetID + "\n" + json);
Gson gson = new Gson();
loadedWidget = gson.fromJson(json, Widget.class);
}
else
{
Log.e(LOG_TAG, "no preferences found for widget: " + key);
}
return loadedWidget;
}
}
【问题讨论】:
标签: android broadcastreceiver sharedpreferences android-appwidget