Android Hilt、Retrofit2 和属性文件问题

Android Hilt, Retrofit2, and properties file issue

我很确定这种情况很常见,但我在任何教程中都没有找到解决方案。也许我以完全错误的方式处理这个问题。

我有一个提供 Retrofit 服务的模块:

    public static RestService providesRestService(){

        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.somedomain.com")
                .addConverterFactory(GsonConverterFactory.create()).build();

        return retrofit.create(RestService.class);
    }

我希望基础 URL 可以通过属性文件进行配置。要使用属性文件,我需要上下文以便我可以访问 AssetManager:

AssetManager assetManager = context.getAssets();
assetManager.open("somefile.properties")
...

所以我可以使用@ApplicationContext 注释:

public static RestService providesRestService(@ApplicationContext){

这应该适用于获取属性,但问题是我有另一个模块提供 class 来处理属性文件:

static PropertiesUtil providesPropertiesUtil(@ApplicationContext Context context) {
        return new PropertiesUtil(context);

所以我想使用那个 class,但是我不能将 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会变成这样:

public 静态字符串 REST_BASE_URL=http://example.com;

而不是

public 静态字符串 REST_BASE_URL="http://example.com";