gpt4 book ai didi

具有不同模块的Android项目(sharedPreferences)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:22 29 4
gpt4 key购买 nike

有谁知道 android 是否支持在一个项目中编译的多个 Android 模块之间共享相同的 sharedpreference?

我有两个共享首选项,目前当我尝试从当前模块外部的共享首选项访问一些数据时,它不起作用,而是创建了一个新的共享首选项

例子

模块一:

 mSharedPreferences = context.getSharedPreferences(
"pref", Context.MODE_PRIVATE);

模块二:

 mSharedPreferences = context.getSharedPreferences(
"pref", Context.MODE_PRIVATE);

它创建了两个首选项文件,而不是两个模块可以共享数据的首选项文件

最佳答案

您可以创建一个通用的 :core 模块并在该模块中添加所有依赖项。

在所有其他模块中实现 :core 模块。

PrefHelpers 类放在 :core 模块中,以便从任何模块访问它们或 您可以使用 BuildConfig.APPLICATION_ID 获取的公共(public)包名称配置 sharedpreference。

 mSharedPreferences = context.getSharedPreferences(
"pref", Context.MODE_PRIVATE);

可以替换为

mSharedPreferences = context.getSharedPreferences(
BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);

您可以将模式用作 Context.MODE_PRIVATE 本身。

确保您的 BuildConfig 来自您的 :core 模块。

如果它解决了您的问题,请回复。

关于具有不同模块的Android项目(sharedPreferences),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481240/

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