android - Android Hilt、Retrofit2 和属性文件问题
问题描述
我有一个我很确定很常见的情况,但我在任何教程中都没有找到解决方案。也许我以完全错误的方式处理这个问题。
我有一个提供改造服务的模块:
public static RestService providesRestService(){
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.somedomain.com")
.addConverterFactory(GsonConverterFactory.create()).build();
return retrofit.create(RestService.class);
}
我希望可以通过属性文件配置基本 URL。要使用属性文件,我需要 Context 以便可以访问 AssetManager:
AssetManager assetManager = context.getAssets();
assetManager.open("somefile.properties")
...
所以我可以使用@ApplicationContext 注释:
public static RestService providesRestService(@ApplicationContext){
这应该适用于获取属性,但问题是我有另一个模块提供一个类来处理属性文件:
static PropertiesUtil providesPropertiesUtil(@ApplicationContext Context context) {
return new PropertiesUtil(context);
所以我想使用那个类,但我不能将 PropertiesUtil 注入另一个提供方法。
我接近这一切都错了吗?
解决方案
我把这一切都错了。更好的方法(在我看来,因为您不需要处理 Context)是使用 buildConfig 变量。
在 app/build.gradle 文件中我添加了:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
buildConfigField "String", "REST_BASE_URL", RELEASE_REST_BASE_URL
}
debug {
applicationIdSuffix ".debug"
debuggable true
buildConfigField "String", "REST_BASE_URL", DEV_REST_BASE_URL
}
}
这将创建一个静态字符串变量,您可以通过自动生成的 BuildConfig.REST_BASE_URL 访问
您可以添加一个 app/gradle.properties 文件以具有以下内容:
DEV_REST_BASE_URL="http://dev.example.com"
RELEASE_REST_BASE_URL="http://example.com"
Gradle 使用精确的值来生成文件,所以你必须添加引号,否则 BuildConfig.java 将是这样的:
公共静态字符串 REST_BASE_URL=http://example.com;
代替
公共静态字符串 REST_BASE_URL="http://example.com";
推荐阅读
- javascript - Angular 6:正确实现 ControlValueAccessor
- excel - 带有活动文件运行时错误的 Application.Goto
- php - mySQL:将值插入具有外键关系的 2 个表中
- c++ - 带有 CMake 的 Clang++-6.0 无法识别 std::string_view
- python - Tensorflow Eager False Postive/Negative Etc Rate
- xslt - 需要 paras 作为部分主级别和子级别标题与 h 级别
- intellij-idea - 转到终端中的当前项目目录
- python - 在 Pandas Python 中重塑 DataFrame
- php - Wordpress rest api,更新信息
- c# - 如何使用 C# 通过串口使用 APDU 命令与智能卡通信