首页 > 解决方案 > 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 注入另一个提供方法。

我接近这一切都错了吗?

标签: androiddependency-injectionretrofitretrofit2dagger-hilt

解决方案


我把这一切都错了。更好的方法(在我看来,因为您不需要处理 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";


推荐阅读