【问题标题】:Not getting saved SharedPreference value from IntentService未从 IntentService 获取保存的 SharedPreference 值
【发布时间】:2015-07-21 16:05:26
【问题描述】:

我正在我的 MainActivity 中创建一个共享首选项,然后我想在我的 IntentService 的共享首选项中保存一个值;然而;我不断得到默认值,而不是我保存的值。

这是我在 MainActivity 中创建 SharedPreference 的代码:

  SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
  prefs.edit().putString("inter", inter).apply();

在我的 IntentService 类中:

 protected void onHandleIntent(Intent intent) {
  SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        final String inter = preferences.getString("inter", "default_no");

}

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    这里的问题很微妙:

    SharedPreferences.Editor#commit 以阻塞方式存储对存储的修改,因此您可以保证在同一线程上查询值的任何其他实例实际上将获得新的。

    SharedPreferences.Editor#apply 异步执行此操作,因此如果您在 另一个 SharedPreferences 实例上获取值的速度过快,它可能无法获取更新后的值。

    提交实际上可能更适合您的情况,因为您没有对偏好进行任何重大更改。如果您需要使用 apply,您可能需要使用 Handler#post 来产生一点延迟。

    干杯。

    【讨论】:

      【解决方案2】:

      尝试使用和编辑器将您的值保存在 SharedPreferences 中

          SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
          SharedPreferences.Editoreditor = pref.edit();
          editor.putString("inter", inter);
          editor.commit();//This will make your value store in SharedPreferences
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-18
        • 2011-03-29
        • 1970-01-01
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多