【问题标题】:Android change preference value and updating display in preference screenAndroid 更改首选项值并更新首选项屏幕中的显示
【发布时间】:2013-07-15 00:07:39
【问题描述】:

我是一名新的 Android 开发人员,我的第一个应用程序即将完成。

我要做的最后一件事是 Tasker 集成。我的集成工作达到了一定程度。

我的应用程序当前设置为作为插件工作并接受来自 tasker 的字符串并使用新字符串更新首选项。这是有效的。

问题是当我重新启动我的应用程序时,首选项的值没有更新。在完全关闭应用并重新启动之前,我无法更新偏好摘要。

所以问题是,我如何强制我的应用从应用的 onResume 中重新加载首选项,还是有更好的方法?

这是接收者更新偏好值的代码:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String album_name = bundle.getString(PluginBundleManager.BUNDLE_EXTRA_STRING_MESSAGE);
prefs.edit().putString("text_default_album", StringUtil.sanitize(album_name)).commit();
Log.d(TAG, "fr: "+prefs.getString("text_default_album", ""));

这是 Activity 的 onResume 中的:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String album_name = prefs.getString("text_default_album", "");
Log.d(TAG, "album_name: "+album_name);

final Preference album = getPreferenceScreen().findPreference("text_default_album");
album.setSummary(album_name);

接收者的清单声明:

    <receiver
            android:name=".receivers.FireReceiver"
            android:exported="true"
            android:process=":background"
            tools:ignore="ExportedReceiver" >

        <!-- this Intent filter allows the plug-in to discovered by Locale -->
        <intent-filter>
            <action android:name="com.twofortyfouram.locale.intent.action.FIRE_SETTING" />
        </intent-filter>
    </receiver>

更新:一旦我删除了接收者的 AndroidManifest.xml 声明中的android:process=":background",可能会遇到这个问题并难以弄清楚的人。它现在按预期工作。

【问题讨论】:

标签: android sharedpreferences preferences


【解决方案1】:

Commit 将新值保存在存储中,但不会更新内存中的值。如果你想要这个功能,你应该使用 apply。阅读更多 herehere

所以你必须更换

prefs.edit().putString("text_default_album", StringUtil.sanitize(album_name)).commit();

prefs.edit().putString("text_default_album", StringUtil.sanitize(album_name)).apply();

希望这会有所帮助...

【讨论】:

  • 这也没有强制更新偏好。当我回到偏好活动时,它仍然显示旧值。当我关闭我的应用并重新启动它时,两者的工作方式相同。
  • @Jayrox 这很奇怪,我唯一能想到的就是替换 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());在您的活动中使用 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);我在某处读到 getApplicationContext() 返回与活动不同的上下文。试试看我不知道还有什么可能......
  • 我刚刚删除了android:process=":background" 代码,现在它可以正常工作了。谢谢!
  • @Jayrox 有个缺点,现在你的接收器在主线程上运行,所以保持 onReceive 尽可能小......
  • -1: “提交将新值保存在存储中,但不会更新内存中的值” - 这不可能。如果是,那么每个get 首选项都将被强制存储。这将完全违背拥有内存副本的目的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多