gpt4 book ai didi

android - 除非退出并重新打开第一个应用程序,否则两个应用程序之间的 SharedPreferences 不会更新

转载 作者:行者123 更新时间:2023-11-29 20:13:37 25 4
gpt4 key购买 nike

我有两个共享首选项的应用程序,我面临的问题是,如果一个应用程序写了一些首选项,而另一个应用程序读取了它们,那么获取的是旧值,除非退出阅读应用程序然后重新打开即:

如果应用 A 正在运行并从首选项中读取一个值:

 ...
prefs = m_context.getSharedPreferences (name, Context.MODE_PRIVATE);
m_retryCount = prefs.getInt(RETRY_COUNT, 0);

假设检索到的值为 10。

现在,如果应用程序 B 运行并写入首选项:

  prefs = cityidCtx.getSharedPreferences (prefsName, Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences.Editor editor = prefs.edit ();
editor.putInt(CityIdHandsetState.RETRY_COUNT, this.m_retryCount);
editor.commit ();

假设写入的值为 20。

现在如果应用程序 A 在应用程序 B 写入新值 20 后再次读取首选项,那么应用程序 A 获得的值仍然是 10。但是如果应用程序 A 退出然后重新打开,那么它读取的值现在是 20。

如何解决这个问题,使应用 A 始终获得更新的值。

最佳答案

你用错了FLAG, that flag isn't used there

Flag for use with createPackageContext(String, int): ignore any security restrictions on the Context being requested, allowing it to always be loaded. For use with CONTEXT_INCLUDE_CODE to allow code to be loaded into a process even when it isn't safe to do so. Use with extreme care!

您正在使用 Context.getSharedPreferences(String name, int mode)其中指出

Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.

您恰好很幸运,因为他们恰好具有相似的值(value)观。你需要使用...

Context.MODE_WORLD_WRITEABLE


然而……你要的其实是Context.MODE_MULTI_PROCESS但是......它在 23 中被弃用并且不允许并发访问数据。

This constant was deprecated in API level 23. MODE_MULTI_PROCESS does not work reliably in some versions of Android, and furthermore does not provide any mechanism for reconciling concurrent modifications across processes. Applications should not attempt to use it. Instead, they should use an explicit cross-process data management approach such as ContentProvider.

因此,您需要使用 ContentProvider。

关于android - 除非退出并重新打开第一个应用程序,否则两个应用程序之间的 SharedPreferences 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34405387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com