Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Hilt、2和属性文件问题_Android_Dependency Injection_Retrofit_Retrofit2_Dagger Hilt - Fatal编程技术网

Android Hilt、2和属性文件问题

Android Hilt、2和属性文件问题,android,dependency-injection,retrofit,retrofit2,dagger-hilt,Android,Dependency Injection,Retrofit,Retrofit2,Dagger Hilt,我有一个很常见的情况,但我在任何教程中都没有找到解决方案。也许我是以完全错误的方式来处理这个问题的 我有一个模块提供改装服务: public static RestService providesRestService(){ Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.somedomain.com") .addConverterFacto

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

我有一个模块提供改装服务:

    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){
这应该可以用于获取属性,但问题是我有另一个模块,它提供了一个类来处理属性文件:

static PropertiesUtil providesPropertiesUtil(@ApplicationContext Context context) {
        return new PropertiesUtil(context);
所以我想使用这个类,但是我不能将PropertiesUtil注入到另一个方法中


我处理这件事全错了吗?

我处理这件事全错了。更好的方法(在我看来,因为您不需要处理上下文)是使用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\u BASE\u URL访问该变量

您可以添加app/gradle.properties文件以具有以下内容:

DEV_REST_BASE_URL="http://dev.example.com"
RELEASE_REST_BASE_URL="http://example.com"
Gradle获取生成文件的确切值,因此您必须添加引号,否则BuildConfig.java将如下所示:

公共静态字符串REST\u BASE\u URL=http://example.com;

而不是


公共静态字符串REST\u BASE\u URL=”http://example.com";

什么是
XXXAppContext
?您好。我编辑了上面的示例代码,使其更有意义,并更改了名称?错误信息是什么?同时向我们展示您的整个
模块
设置(注释等)。事实上,您是正确的!错误是关于注入一个静态函数(我的提供函数),但我不认为注入是一个成员变量。这是可行的,但最后我决定将它们作为buildconfig变量抛出,通过app-level gradle.properties文件进行控制