【问题标题】:Getting app configuration from a file从文件中获取应用配置
【发布时间】:2018-06-06 11:14:32
【问题描述】:

我需要从一个可能是 xml 文件的文件中获取一些 Config 来创建 build 。我不能使用buildVarient,因为构建变量不是固定的。以下是我需要导入的属性。

  1. 应用程序 ID:- 在 build.gradle.
  2. 基本 URL:- 网络请求的基本 URL。
  3. 应用名称:- 清单中的应用名称

要求是为一个人创建一个 apk。所以构建过程应该很简单。这就是为什么我正在考虑创建一个config 文件并从文件中引用上述所有 3 个属性。 3个都可以吗?如果是怎么办? .请帮忙 。

【问题讨论】:

    标签: android android-studio android-gradle-plugin


    【解决方案1】:

    我在build.gradle 中使用类似的口味:

    Properties versionProps = new Properties()
    versionProps.load(new FileInputStream(file('config.conf')))
    def properties_versionCode = versionProps['VERSION_CODE'].toInteger()
    def properties_versionName = versionProps['VERSION_NAME']
    
    versionName properties_versionName
    versionCode properties_versionCode
    

    请看第 2、3、4 行。

    这是config.conf 文件:

    VERSION_NAME=1.0.0
    VERSION_CODE=100
    

    两个文件应放在同一文件夹级别。


    对于设置应用程序名称和基本 url,我会使用单独的项目文件夹,更多关于它的讨论 here


    您还可以创建自定义构建字段,以便通过调用 BuildConfig.{FIELD} 在代码中可见。

    defaultConfig {
        ...
        buildConfigField "String", "OS", '"android"'
    }
    

    然后 BuildConfig 看起来像这样:

    public final class BuildConfig {
        public static final boolean DEBUG = Boolean.parseBoolean("true");
        public static final String APPLICATION_ID = "com.example.app";
        public static final String BUILD_TYPE = "debug";
        public static final String FLAVOR = "";
        public static final int VERSION_CODE = 1;
        public static final String VERSION_NAME = "1.0";
        // Fields from default config.
        public static final String OS = "android";
    }
    

    更多here.

    【讨论】:

    • 很公平。我应该在哪里使用Properties versionProps = new Properties()?你能添加整个代码块吗?
    • 我应该把config.properties文件放在哪里。我使用了资产,我在 build.gradle 中得到了unable to resolve class android.content.res.AssetManager
    • 好的所以我把config.properties放在app文件夹下。它在 gradlle 工作。谢谢你的芽。我如何在 java 类中访问它?是的,祝贺 6K 任务完成。
    • 我可以在资产中使用这个文件吗?如果是,那么我将如何将其加载到build.gradle
    • 我在资产中使用了它。它的工作。使用 versionProps.load(new FileInputStream(file('/src/main/assets/configs/config.properties'))) 。感谢您的支持。我这里需要一个问题,请查看this question
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2023-03-14
    • 2011-03-08
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多