android - 具有相同 sharedUserId 的应用程序之间的 Sharedpreference

标签 android sharedpreferences

我正在做一个项目,我有一个核心应用程序和多个不同 apk 的插件。我想在我的不同模块之间共享一些数据(例如用户名或他的电子邮件地址)。我试图通过将其添加到他们的 list 中来为他们提供相同的 sharedUserId :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.giom.mymodule1"
          android:sharedUserId="com.giom">

我的模块非常相似,都以相同的方式保存和尝试检索它们的共享首选项:

Context mainAppContext = getActivity().getApplicationContext().createPackageContext("com.giom.mainapp", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPreferences = mainAppContext.getSharedPreferences("sharedpreferences", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
sharedPreferences.edit().putString("EMAIL", email).commit();

Context mainAppContext = getActivity().getApplicationContext().createPackageContext
("com.giom.mainapp", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPreferences = mainAppContext.getSharedPreferences("sharedpreferences", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
String email = sharedPreferences.getString("EMAIL", null)

这两个代码都来 self 的 PreferenceActivities,它们是 FragmentActivity。问题是这似乎有效;例如,如果我更改其中一个模块中的值并重新启动手机,另一个模块就会更改。但是,如果我打开其中一个 Activity ,然后打开另一个 Activity ,更改其中一个 Activity 的值并返回到另一个 Activity ,我仍然会得到旧的 Activity ,直到我重新启动。它的工作就像有某种缓存...

我的直觉是我没有使用正确的上下文,我应该用其他东西替换 getActivity() 但我不知道是什么......

预先感谢您的帮助。

PS:我读到过这种方法已经过时了,所以如果你知道我应该如何分享我的数据,请随时告诉我 :)

最佳答案

好的,在这里找到了答案:https://stackoverflow.com/a/11025235/3628452

The getSharedPreferences method appears to check for a .bak file to load the preferences from. This is why it says in the documentation that it will not work across multiple processes; to minimize I/O, it loads the prefs ONCE when you grab them and only backs them up when you close your application/activity

这意味着如果我不打开/关闭我的模块,我将仍然拥有打开它时 bak 文件中的数据...

关于android - 具有相同 sharedUserId 的应用程序之间的 Sharedpreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23906186/

相关文章:

java - 重新启动应用程序后更新共享首选项

android - Android 运行时更改的自定义软键盘

java - 是否可以从java类调用android类?

java - 使用 Mockito 在 Android 上模拟 socket.io 服务器

android - 仅在首次启动时显示 Activity

具有共享首选项的 Flutter 依赖注入(inject)

Android Studio 默认缺少新建项目向导

android - 在 WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER 出现错误

android - 如何从 SharedPreferences 计算具有整数值的键

android - 没有找到 SharedPreferences.getStringSet()?