1

我试图找到有关此问题的解释,但找不到任何东西。

我有一个在后台工作的远程服务。该服务从 SharedPreference 中读取一些首选项。

当我从 PreferenceActivity 更改首选项(活动和服务属于同一个应用程序和同一个包)时,我遇到了这个问题。我更改了首选项并正确保存,但是只要服务读取该首选项(服务从不修改首选项,它只会修改一些无法从 PreferenceActivity 修改的内部首选项),首选项就会“重置”并且服务获取重置的值。

CheckBoxPreference 正在发生这种情况。我不知道这是否会发生在其他类型的偏好中,因为我没有任何偏好。

更改首选项后,我应该重新启动服务吗?或者我需要“刷新”服务中的偏好?也许这是与使用 HoloEverywhere 相关的问题?

要获取 SharedPreference 对象,我使用以下代码:

PreferenceManager.wrap(context, getSharedPreferencesName(context), Context.MODE_MULTI_PROCESS);

此代码特定于 HoloEverywhere,它等于:

context.getSharedPreferences(getSharedPreferencesName(context), Context.MODE_MULTI_PROCESS);

'getSharedPreferencesName()' 只返回一个由“package.name_preferences”组成的字符串。

谢谢你。

4

1 回答 1

3

I have a remote service that is working in the background.

Why did you make your service be remote?

I change the preference and it is saved correctly, but as soon as the service reads that preference (the service never modifies the preferences, it only modifies some internal preferences that cannot be modified from the PreferenceActivity) the preference is 'resetted' and the service gets the resetted value.

That's because you made your service remote. Simply remove the android:process attribute from your manifest, to have all your components run in the same process, and this problem will go away. Along the way, you will make the user happier, because you won't be consuming as much RAM and battery.

After I change the preference I should restart the service? Or I need to 'refresh' the preferences in the service?

If you truly have a legitimate reason for having a remote service -- and IMHO there's a greater chance that I will spontaneously regrow my hair -- you will need to restart the service's process, AFAIK. SharedPreferences are cached per process, and I don't know of a way to force Android to reload SharedPreferences from disk except by restarting the process.

Or, you could not have a remote service. The choice is yours.

于 2012-11-09T00:29:22.153 回答